Problem converting from int to float

前端 未结 6 1873
[愿得一人]
[愿得一人] 2021-01-02 00:27

There is a strange behavior I cannot understand. Agreed that float point number are approximations, so even operations that are obviously returning a number without decimal

6条回答
  •  不思量自难忘°
    2021-01-02 00:50

    this code...

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                float result = 195.95F*100;
                int intresult = (int)(195.95F * 100);
            }
        }
    }
    

    give this IL

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       14 (0xe)
      .maxstack  1
      .locals init ([0] float32 result,
               [1] int32 intresult)
      IL_0000:  nop
      IL_0001:  ldc.r4     19595.
      IL_0006:  stloc.0
      IL_0007:  ldc.i4     0x4c8a
      IL_000c:  stloc.1
      IL_000d:  ret
    } // end of method Program::Main
    

    look at IL_00001 -> the compier has done the calc.. Otherwise there are the decimal -> binary conversion problem

提交回复
热议问题