【发布时间】:2009-01-25 00:39:16
【问题描述】:
家庭作业问题:
- Cygwin GNU GDB
- Cygwin GNU GCC
尝试根据 2 的 A 次方和 B 2 次方的平方根来确定 斜边 C 的长度。
示例输入:
输入直角三角形两条边的长度:2.25 8.33
答案:
斜边的长度为:8.628523
- 问题:当我指定与上面相同的输入时,结果不是 same - 输出是 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);
}
【问题讨论】:
-
你到底为什么将指针传递给浮点数而不是按值传递?
-
@Andrew - 我同意;确实,鉴于代码也在修改值,这非常可怕。