C#中的数值数据类型比较

时间:2019-09-20 13:07:52

标签: c# floating-point comparison-operators

能否请您解释以下代码的结果:

    float f = 1.56898138E+09f;
    double d = 1.56898138E+09;
    int i = 1568981320;

    bool a = f > i; //false 
    bool b = d > i; //true
    bool c = (int)f > i; //true

为什么是a == false

2 个答案:

答案 0 :(得分:4)

从int到float有隐式转换。这是有损隐式转换的罕见示例。

(float)1568981320 = 1568981376f,该值与f相同,因此不能大于或小于该值。

答案 1 :(得分:2)

好吧,int使用 all 32位存储整数值

 1568981320 == 1011101100001001100000101001000 (binary)

float仅将23https://en.wikipedia.org/wiki/Single-precision_floating-point_format与{em> 一起使用时,因此 最初的1应该四舍五入:

1011101100001001100000101001000

因此,在舍入时,我们应该丢掉 1011101100001001100000101001000 ^ ^ from this on we should throw the "1001000" bits away | this 1 can be skipped since float assumes that the 1st bit is always 1 并添加1001000

1

这是 1011101100001001100000101001000 - original value (1568981320) 1011101100001001100000110000000 - rounded value (1568981376) ^ ^ will be stored in float 的值,比原始1568981376