2015-04-01 69 views
-1

我的一项任务是创建一个使用辛普森1/3规则找到总和的c程序。我遇到了我无法修复的问题。有更多经验的人能否指出我的方向正确?辛普森规则集成

理论上我的代码集成了y = ax^2 + bx + c,其中用户选择a,b,c的值,然后用户选择上下限[d,e]。然后用户选择将该区域分割成更多矩形的n值(我们在课堂中使用的值为100,因此该区域被分割成100个矩形)。之后它贯穿辛普森的规则并打印出总和。

//n is required number of iterations. 

#include<stdio.h> 
#include<conio.h> 
#include<math.h> 

double integral (int a,int b,int c,int d,int e,int n) 

int main() 
{ 
    double a, b, c, d, e, n; 

    printf("Please select values for y=ax^2+bx+c"); 
    printf("Please select value for a"); 
    scanf("%d", &a); 
    printf("Please select value for b"); 
    scanf("%d", &b); 
    printf("Please select value for c"); 
    scanf("%d", &c); 
    printf("Please select value for the upper limit"); 
    scanf("%d", &d); 
    printf("Please select value for the lower limit"); 
    scanf("%d", &e); 
    printf("Please select the number of rectangles for the Simpson's Rule (Input 100)"); 
    scanf("%n", &n); 

    int i; 
    double sum=0,length=(double)(d-e)/(n),ad,bd,cd,dd; 

    ad=(double)a; 
    bd=(double)b; 
    cd=(double)c; 
    dd=(double)d; 
    for (i=0;i<n;i++) 
    { 
     sum+=(ad*(dd*dd+2*dd*length*i+length*length*i*i)+bd*(dd+length*i)+cd)*length; 
     printf("the value is = %d",sum); 
    } 
    return sum; 
} 

回答

1

为什么你认为这

scanf("%e", &e); 

应该是这个样子?

scanf()功能需要一个格式说明,以配合,你的情况,你要的值存储在double变量,您需要的"%lf"符,扫描输入,这样所有的scanf()的应更改为

scanf("%lf", &whateverDoubleVariableYouWantToStoreTheResultIn); 

你不需要从给定类型相同类型的变量投,喜欢这里

dd=(double)d; 

而且也,你必须知道,那scanf()返回一个值,你不应该忽略它,因为如果输入错误,你的程序将会出现问题,你应该在库手册或C标准中检查scanf()以更好地理解如何使用它。

+1

它shouldve一直的scanf( “%d”,&e);我有麻烦的代码在后整合。 – 2015-04-01 20:45:35

1

除了@iharob细建议:

  1. 变化n类型

    // double a, b, c, d, e, n; 
    double a, b, c, d, e; 
    int n; 
    
  2. 调整输入代码

    // and previous lines 
    if (1 != scanf("%lf", &e)) // %d --> %lf 
        Handle_InputError(); 
    printf("Please select the number of rectangles for the Simpson's ... 
    if (1 != scanf("%d", &n) // %n --> %d 
        Handle_InputError(); 
    
  3. 调整输出

    // printf("the value is = %d",sum); 
    printf("the value is = %e",sum); // or %f 
    
  4. 次要位

    // int main() 
    int main(void) // or int main(int argc, char *argv[]) 
    
    // return sum; returning a double here is odd 
    return 0;