-2
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;
}
4

3 回答 3

1

首先声明 x 以在主函数中使用它

float 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;
}
于 2013-03-16T05:12:59.127 回答
1

如果 x 不能在主函数中声明,则在全局范围内声明,

float x;

int main( ) {
  ...
}
于 2013-03-16T07:56:47.950 回答
0
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;
}
于 2013-03-16T08:02:01.670 回答