Double to Float Type Conversion - 为什么我不能将(double)20150813.00转换为(float)20150813.00?

时间:2015-08-15 09:43:31

标签: c++ floating-point

为什么20150813.00会转换为20150812.00000020150708.000000会正确转换为20150708.000000

代码示例:

#include <stdio.h>
#include <iostream>
int main()
{
        double one_o = 20150813.00;
        double two_o = 20150708.00;
        float one = (double)one_o;
        float two = (double)two_o;
        std::cout << std::fixed << "one_o = " << one_o << " one = " << one << std::endl;
        std::cout << "two_o = " << two_o << " two = " << two << std::endl;
        return 1;
}

输出是 -

one_o = 20150813.000000 one = 20150812.000000
two_o = 20150708.000000 two = 20150708.000000

帮助我理解double to float类型转换!

编辑: std::numeric_limits<float>().max()报告340282346638528859811704183484516925440.000000作为float中存储的最大值,这远远超出我试图存储的内容:

1 个答案:

答案 0 :(得分:4)

float可以存储比20150813更大的数字,但它无法存储精确的大整数。

假设使用IEEE 754,单精度float可以精确地存储最多2 24 的整数,即16777216。比它大的整数可能会失去一些精确度。