我运行了它,一切似乎都很好——除了它一直给我 1 的误差范围。它为什么这样做?
该程序应该提示用户输入 3 的立方根的估计值,并且它使用牛顿近似法来显示达到近似值需要多少次尝试。经过 500 次尝试或误差幅度小于 0.000001 后,它应该退出循环。但为什么误差幅度没有改变?
这是我的代码:
#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;
}
}
最佳答案
abs()
处理 int
并返回一个 int
,您需要 fabsf()
。
同样,pow()
适用于 double
,您应该使用 powf()
。
另一个错误是编写 1/3
并期望结果为 0.333...。 1
和 3
是 int
文字,因此执行的操作是整数除法。您需要使用float
文字,例如1.0f/3.0f
。
这就是类型兼容性。然而,我可以看到另一个错误:您期望 e
以某种方式记住它的公式并自动重新应用它。命令式语言不是这样工作的:当您编写 e = Something
时,“something” 就会被计算出来并一次性存储在 e
中。您对 a
的操作正确,现在只需将 e=abs(...);
放入 while
循环中即可每次更新它时间。
关于c - 为什么我的 C 程序总是给出 1 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28256225/