2015-01-31 49 views
-3

我跑了它,一切似乎都很好 - 除了它一直給我一個1的誤差。爲什麼它這樣做?爲什麼我的C程序不斷給我1作爲錯誤?

該程序應該提示用戶輸入3的立方根的估計,並且它使用牛頓的近似方法來顯示進行近似所花費的嘗試次數。經過500次嘗試或誤差小於0.000001,應該退出循環。但是,爲什麼錯誤幅度不會改變?

這裏是我的代碼:與int小號

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

int main() 
{ 
    float a, i, e;      //declare float variables 
    printf("Consider the function f(x) = x^3 - 3 = 0.\n"); 
    printf("Simplifying, we get x^3 = 3.\n"); 
    printf("Simplifying it further, we get x = 3^(1/3).\n"); 
    printf("Enter your estimate of the root: "); 
    scanf("%f", &a);     //prompt user to guestimate 
    printf("So you're saying that x = %f.\n", a); 
    i=0;        //initiate attempt counter 
    e=abs((a-pow(3, (1/3)))/pow(3, (1/3))); //margin of error formula 
    while (e>=0.000001 && i<=500)  //initiate while loop with above expressions 
    { 
     if (a!=pow(3, (1/3))) 
     { 
      printf("Attempt %f: ", i); 
      a = a - (pow(a, 3) - 3)/(3*pow(a, 2)); 
      printf("%f, ", a); 
      printf("%f margin of error\n", e); 
      i=i+1; 
     } 
     else 
      break; 
    } 
} 
+3

在進入循環之前'e'被設置並且從未更新過 – 2015-01-31 20:35:19

+2

C中'(1/3)'的值是多少? – Barmar 2015-01-31 20:35:19

+0

'1/3'爲0.因此,'pow(3,1/3)'總是1.在嘗試編寫非平凡程序之前,最好學習語言基礎知識。 – 2015-01-31 20:36:16

回答

4

abs()交易,並會返回一個int,你需要。

以同樣的方式,pow()double s,您應該使用powf()

另一個錯誤是編寫1/3並期望0.333 ...因此。 13int文字,所以執行的操作是整數除法。您需要使用float文字,例如1.0f/3.0f

這就是類型兼容性。但是我可以看到另一個錯誤:您希望e以某種方式記住它的公式並自動重新應用它。這不是命令式語言的工作方式:當你編寫e = something時,「東西」被計算並存儲在e中。您正在爲a正確執行此操作,現在只需在while循環內攜帶e=abs(...);以每次更新它。

相關問題