C's pow() function as per header file <math.h> not working properly

一世执手 提交于 2019-12-29 09:38:11

问题


I see that for the following code produces the result as below, any idea on why is the output like 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

回答1:


Use the round() function before casting to int, else the trailing digits will just get truncated.




回答2:


As with every one of the billion other questions on SO to do with floating point :-), the answer is that not all numbers can be represented exactly.

And, even if they can be represented exacly, you may get a bad result from something like pow which may work within a loop. In other words, no matter how small the error on an operation, if you do it a lot of times, the error becomes large.

Try printing out the return from pow(10,4) with a %.50f or other floating point specifier, and I'll guarantee you'll see something like 9999.9999999237623465 instead of 10000.

For what it's worth, the correct results are produced under gcc 3.4.4 under CygWin so it's likely that you're using a less-exact implementation of pow.



来源:https://stackoverflow.com/questions/3509423/cs-pow-function-as-per-header-file-math-h-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!