c - 不使用 C 中 math.h 中的 sqrt() 的预定义平方根函数

标签 c windows math

家庭作业问题:

  • Cygwin GNU GDB
  • Cygwin GNU GCC

尝试根据 2 的 A 次方和 2 的 B 次方的平方根确定斜边 C 的长度。

示例输入:

输入直角三角形两条边的长度:2.25 8.33

答案:

斜边的长度为:8.628523

  • 问题:当我指定与上面相同的输入时,结果不相同 - 输出为19.84.9596

完整代码如下:

float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}


int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}

最佳答案

您(应该是?)使用的平方根算法称为 Newton's method 。你的 if 语句应该是一个 while 循环。

替换

if (e*e > 0.001)
{
        nx = (cx +*s/cx)/2;
        return nx;
} else {
        return nx;
}

使用 while 循环迭代执行相同的操作,但包括重新计算 e。

我会给你工作代码,但你说这是家庭作业。如果您无法让它工作,请发布您的新代码,我很乐意帮助您排除故障。

关于c - 不使用 C 中 math.h 中的 sqrt() 的预定义平方根函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/476966/

相关文章:

c - 在 if 中使用预递减条件调用函数

C 函数 fopen();错误: too many arguments to the function

c# - 如何使安装文件(由 IExpress 创建)在另一台计算机上以管理员身份运行

windows - 如何升级 Windows Netbeans 的 Subversion 版本

python - 使用python解决一道数学题: sum up to a value as close as possible

algorithm - 欧拉计划问题 233

c - 进程内存检查

c - 结构中指针变量的大小

c# - 显示Windows Dialog后如何处理?

python - 用于计算设定范围内指数极限的脚本