Is “(float)integer == integer” guaranteed to be equal in C#?

前端 未结 5 2054
有刺的猬
有刺的猬 2021-01-07 20:05

While \"we all know\" that x == y can be problematic, where x and y are floating point values, this question is a bit more specific:

5条回答
  •  萌比男神i
    2021-01-07 20:44

    I ran this code without an exception being thrown:

    for (int x = Int16.MinValue; x < Int16.MaxValue; x++)
    {
     float r = x;
     if (r != x)
     {
      throw new Exception("Failed at: " + x);
     }
    }
    

    Still waiting on (didn't complete this test because it took too long, never threw an exception though while running):

    for (long x = Int64.MinValue; x < Int64.MaxValue; x++)
    {
     float r = x;
     if (r != x)
     {
      throw new Exception("Failed at: " + x);
     }
    }
    

    Went back and ran your example with a caveat, this was the output:

    [Exception: not equal 16777217 ?= 1.677722E+07 ?= 16777216]
    
    for (int i = 0; i < int.MaxValue; i++)
    {
     float f = i;
     if ((int)f != i) throw new Exception("not equal " + i + " ?= " + f + " ?= " + (int)f);
    }
    

提交回复
热议问题