【问题标题】:Numeric data types comparison in C#C#中的数值数据类型比较
【发布时间】:2019-09-20 13:07:52
【问题描述】:

能否解释一下下面代码的结果:

    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

【问题讨论】:

  • float 为 32 位浮点数,double 为 64 位浮点数,int 为 32 位整数。
  • 因为float 不够精确,无法代表1568981320。当1568981320 转换为float 时,结果为1568981380,因此f == iint 隐式提升为float,而不是相反)。顺便说一句,double 足够精确,可以准确地表示所有可能的 int 值。

标签: c# floating-point comparison-operators


【解决方案1】:

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

(float)1568981320 = 1568981376f,与f 的值相同,所以不会更大或更小。

【讨论】:

    【解决方案2】:

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

     1568981320 == 1011101100001001100000101001000 (binary)
    

    float 使用23 位时only 总是1 (https://en.wikipedia.org/wiki/Single-precision_floating-point_format),所以 初始的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 的值,比原来的1568981320

    更大

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多