2015-04-01 45 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;