平方根近似(C)

时间:2013-03-16 05:11:23

标签: c

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

我的函数不会编译,因为它在main函数中一直说“x is unclared”(无法修改),我做错了什么?

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

3 个答案:

答案 0 :(得分:1)

首先声明x在main函数

中使用它
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;
}

答案 1 :(得分:1)

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

float x;

int main( ) {
  ...
}

答案 2 :(得分: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;
}