家庭作业问题:
- 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/