0

I'm starting coding in C and I was doing an exercise, but saw a miscalculation testing this code:

int main(){

int number;
int square;

printf("Pick a number: ");
scanf("%d",&number);

while(number<=0)
{
    printf("ERROR: The number MUST be greater than zero\nPick a number greater than zero: ");
    scanf("%d",&number);
}

square = pow(number,2);

printf("\nThe square of the number is: %d\n\n",square);
system("pause");

return 0;}

now... everything works just fine, but when I use the number "5", it shows the result "24", when it should be "25". anyone knows why this happen?

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
JaviScript
  • 23
  • 2

4 Answers4

2

pow takes double arguments and returns a double. So you're getting a rounding error.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
  • great, thanks. now that I've changed `int` to `double` it works, although I don't understand why there is a rounding error beacause 5*5 is 25 and have nothing to round. – JaviScript Mar 19 '17 at 23:29
  • Try printing the double with `"%.20f"`. Since it rounded down to 24, I'm guessing you'll get something like 24.9999999999998. – Tom Zych Mar 19 '17 at 23:42
0

The function pow() takes a double value as an input parameter and returns a double also, as it is defined in the C standard library. However, the variable you pass to (number) is an int variable. This results in a rounding error as the compiler uses a non-integral value for the calculation process.

To get around this error, declare number with type double instead of int:

double number;

That should sort the rounding issue.

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31
0

Because in C standard library, pow is defined as a function taking double arguments and returning a double value. Even if nothing is required by the standard concerning the implementation, common implementations use (more or less) the following formula: pow(x, y) = exp(y * log(x)). That means that even if you pass integer values, the internal operations will use non integer values, and rounding errors will occur.

That is what happens with your current implementation with 5. To make sure of it, just print the result as a double:

double dsq = pow(5, 2);
printf("%f", dsq);

dsq (in your implementation) should be slightly off and when rounded you get 24

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
-2

Hum I think you should cast pow in int :

square = (int)pow(number,2);
newuser
  • 67
  • 3
  • 8