C pow () function according to <math.h> file header does not work properly
I see that for the following code we get the result, as shown below, any idea of ββwhy the output is this:
#include <stdio.h> #include <math.h> int main() { int i = 0; for(i = 0; i < 10; i++) { printf("%d\t\t\t%d\t\t\t", i, (int)pow(10, i)); printf("%f\n", pow(10, i)); } return 0; } Outputs:
0 1 1.000000 1 10 10.000000 2 99 100.000000 3 1000 1000.000000 4 9999 10000.000000 5 100000 100000.000000 6 1000000 1000000.000000 7 9999999 10000000.000000 8 99999999 100000000.000000 9 999999999 1000000000.000000 Use the round() function before casting to int , otherwise the final digits will simply be truncated.
Like every one of the billions of other floating point SO questions :-), the answer is that not all numbers can be represented exactly.
And even if they can be presented exacly, you may get a bad result from something like pow , which can work in a loop. In other words, no matter how small the error in the operation is, if you do it many times, the error gets big.
Try printing the return from pow(10,4) using %.50f or another floating point specifier, and I guarantee that you will see something like 9999.9999999237623465 instead of 10000 .
Why this is necessary, the correct results are produced in gcc 3.4.4 under CygWin, so you are probably using a less accurate implementation of pow .