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?
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