-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;
}
}
在進入循環之前'e'被設置並且從未更新過 – 2015-01-31 20:35:19
C中'(1/3)'的值是多少? – Barmar 2015-01-31 20:35:19
'1/3'爲0.因此,'pow(3,1/3)'總是1.在嘗試編寫非平凡程序之前,最好學習語言基礎知識。 – 2015-01-31 20:36:16