C'S POW()函数每头文件<&math.h中GT;工作不正常 [英] C's pow() function as per header file <math.h> not working properly

查看:198
本文介绍了C'S POW()函数每头文件<&math.h中GT;工作不正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到以下code产生如下的结果,为什么是任何想法的输出也是这样吗?

 的#include<&stdio.h中GT;
#包括LT&;&math.h中GT;诠释主(){
    INT I = 0;
    对于(I = 0; I&小于10;我++){
        的printf(%d个\\ t \\ t \\ t%d个\\ t \\ t \\ t的,我,(INT)POW(10,I));
        的printf(%F \\ N,POW(10,I));
    }
    返回0;
}

输出:

  0 1 1.0000001 10 10.0000002 99 100.0000003 1000 1000.0000004 9999 10000.0000005 100000 100000.0000006百万1000000.0000007 9999999 10000000.0000008 99999999 100000000.0000009 999999999 1000000000.000000


解决方案

至于对这样十亿其他问题做浮点:-)每个人,得到的答复是,并非所有的数字可以重新$ P $正是psented。

和,即使它们的可以的是重新presented exacly,你可能会得到类似 POW 这可能工作一坏的结果一个循环中。换句话说,不管多么小的一个操作错误,如果你这样做了很多次,误差变大。

尝试打印出从 POW(10,4)%的回报率。50F 或其它浮点符,我会保证你会看到类似 9999.9999999237623465 而不是 10000

有关它的价值,正确的结果是根据GCC 3.4.4在Cygwin下产生的,因此很可能是因为您使用的 POW

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

解决方案

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.

这篇关于C'S POW()函数每头文件&LT;&math.h中GT;工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆