-2

My function won't compile as it keeps saying "x is undeclared" in the main function (can't be modified), what am I doing wrong?

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

For completeness, this is the implementation of the squareRoot function:

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;
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

1

declare x first to use it inside main function

float x;

Like this with in the scope or you can declare globally

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;
}
Civa
  • 2,058
  • 2
  • 18
  • 30
1

If x cannot be declared in the main function, then declare it in a global scope,

float x;

int main( ) {
  ...
}
Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
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;
}
Abhineet
  • 5,320
  • 1
  • 25
  • 43