平方根近似(C)
我的函数不会编译,因为它在主函数中一直说“x未声明”(不能修改),我做错了什么平方根近似(C),c,C,我的函数不会编译,因为它在主函数中一直说“x未声明”(不能修改),我做错了什么 float squareRoot(float value, float error){ float estimate; float quotient; estimate = 1; float difference = abs(value - estimate * estimate); while (difference > error){
float squareRoot(float value, float error){
float estimate;
float quotient;
estimate = 1;
float difference = abs(value - estimate * estimate);
while (difference > error){
quotient = value/estimate;
estimate = (estimate + quotient)/2;
difference = abs(value - estimate * estimate);
}
return difference;
}
首先声明x以在主函数中使用它
int main(){
printf("\nsquare root test 1: enter a number\n");
scanf("%f",&x);
printf("root(%.2f) = %.4f\n", x, squareRoot(x, .001));
getchar();
return 0;
}
像这样,您可以在范围内声明,也可以全局声明
float x;
如果x不能在主函数中声明,则在全局范围中声明
int main(){
float x;
printf("\nsquare root test 1: enter a number\n");
scanf("%f",&x);
printf("root(%.2f) = %.4f\n", x, squareRoot(x, .001));
getchar();
return 0;
}
另外,如果无法修改
main()
,则需要在文件范围内声明x
。@H2CO3您所说的main()
不能修改是什么意思?@icepack阅读问题。“在主函数中(不能修改),[…]”
float x;
int main( ) {
...
}
int main(){
float x ; /* You missed this :-D */
printf("\nsquare root test 1: enter a number\n");
scanf("%f",&x);
printf("root(%.2f) = %.4f\n", x, squareRoot(x, .001));
getchar();
return 0;
}