铸造变化的价值奇怪

Kla*_*aus 5 c++ casting

为什么a1=72不是73在C++代码本(可怕的)片段?

#include <iostream>
#include <string>

using namespace std;

int main (int argc, char* argv[])
{   
    double       a  = 136.73;
    unsigned int a1 = (100*(a-(int)a));

    cout << (a-(int)a)     << endl; // 0.73
    cout << 100*(a-(int)a) << endl; // 73
    cout << a1             << endl; // 72 !
}
Run Code Online (Sandbox Code Playgroud)

您可以在http://codepad.org/HhGwTFhw执行它

Fré*_*idi 8

如果提高输出精度,您将看到(a - (int) a)打印件0.7299999999999898.

因此,这个值的截断(当你将它转换为an时得到的int)确实如此72.

(这里更新了键盘.)


fre*_*low 5

这是一个常见的精度问题.文字136.73实际上代表数字

136.729999999999989768184605054557323455810546875
Run Code Online (Sandbox Code Playgroud)

并且结果a-(int)a不是0.73(即使这是显示的内容),而是

0.729999999999989768184605054557323455810546875
Run Code Online (Sandbox Code Playgroud)

当你乘以时100,你得到

72.9999999999989768184605054557323455810546875
Run Code Online (Sandbox Code Playgroud)

因为从double转换为int会切断小数点后的所有内容,所以你得到了72.