作业问题:
试图从A的幂2和B的2的平方根确定斜边 C 的长度.
输入示例:
输入直角三角形两边的长度:2.25 8.33
回答:
斜边的长度为:8.628523
完整代码如下:
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);
}
Run Code Online (Sandbox Code Playgroud)
您(应该是?)使用的平方根算法称为牛顿方法.你的if语句应该是while循环.
更换
if (e*e > 0.001)
{
nx = (cx +*s/cx)/2;
return nx;
} else {
return nx;
}
Run Code Online (Sandbox Code Playgroud)
使用while循环迭代地执行相同操作,但包括重新计算e.
我会给你工作代码,但你说这是功课.如果您无法使用它,请发布您的新代码,我们将很乐意帮助您排除故障.
| 归档时间: |
|
| 查看次数: |
6111 次 |
| 最近记录: |