c - 为什么我的 C 程序总是给出 1 错误?

标签 c debugging math

我运行了它,一切似乎都很好——除了它一直给我 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...。 13int 文字,因此执行的操作是整数除法。您需要使用float文字,例如1.0f/3.0f

这就是类型兼容性。然而,我可以看到另一个错误:您期望 e 以某种方式记住它的公式并自动重新应用它。命令式语言不是这样工作的:当您编写 e = Something 时,“something” 就会被计算出来并一次性存储在 e 中。您对 a 的操作正确,现在只需将 e=abs(...); 放入 while 循环中即可每次更新它时间。

关于c - 为什么我的 C 程序总是给出 1 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28256225/

相关文章:

c - 如何在 C 中使用指针获取多维数组的输入并打印数组?

c# - 防止 DebuggerStepThroughAttribute 应用于我的非 xsd 生成的分部类?

python - 旋转 glViewport?

java - 有人可以向我解释为什么 0.15 - 0.10 = 0.049 吗?

java - 检查像素坐标偏移的高效代码

c - OCIStmtPrepare 返回 OCI_INVALID_HANDLE

有人可以解释一下这段代码的作用吗?

javascript - Node.js 堆栈跟踪不包含用户代码

javascript - 为什么 firebug 调试有时有效有时无效?

c - 缓冲区溢出;避免溢出攻击