如果我先给浮点计算的值赋给变量,然后再将其赋给具有隐式类型转换的无符号int,我将得到一个答案。但是,如果我将相同的计算直接分配给unsigned int,又使用隐式类型转换,则会得到不同的答案。

下面是我编译并运行以演示的示例代码:

#include <iostream>



int
main( int argc, char** argv )
{
    float   payloadInTons = 6550.3;


    //  Above, payloadInTons is given a value.
    //  Below, two different ways are used to type cast that same value,
    //  but the results do not match.
    float tempVal = payloadInTons * 10.0;
    unsigned int right = tempVal;
    std::cout << "    right = " << right << std::endl;


    unsigned int rawPayloadN = payloadInTons * 10.0;
    std::cout << "    wrong = " << rawPayloadN << std::endl;


    return 0;
}

有谁知道为什么“对”是对的,“错”是错的?

顺便说一句,如果重要的话,我在Ubuntu 14.04 LTS上使用gcc 4.8.2。

最佳答案

您正在使用double文字。使用正确的float文字,一切都很好。

int
main( int argc, char** argv )
{
    float   payloadInTons = 6550.3f;
    float tempVal = payloadInTons * 10.0f;

    unsigned int right = tempVal;
    std::cout << "     right = " << right << std::endl;

    unsigned int rawPayloadN = payloadInTons * 10.0f;
    std::cout << "also right = " << rawPayloadN << std::endl;


    return 0;
}

输出 :
     right = 65503
also right = 65503

10-08 11:14