定义一个float类型的变量=0.7,结果在IL中却是0.69999999。
乘以10之后,获取整数值。得到的却是6。通过查看IL,竟然被转换成double类型再转换。就变成6了。
Demo:
IL:
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // 代码大小 93 (0x5d) .maxstack 2 //定义变量 .locals init ([0] float32 val, [1] int32 i) IL_0000: nop IL_0001: ldc.r4 0.69999999 //将0.69999999赋值给第0个变量。明明定义的是0.7 IL_0006: stloc.0 IL_0007: ldc.i4.s 10 /将10赋值给第一个变量 IL_0009: stloc.1 //double类型的0.7 IL_000a: ldc.r8 0.69999999999999996 IL_0013: ldloc.1 IL_0014: conv.r8 IL_0015: mul IL_0016: call float64 [mscorlib]System.Math::Floor(float64) IL_001b: call void [mscorlib]System.Console::WriteLine(float64) IL_0020: nop IL_0021: ldloc.0 IL_0022: call void [mscorlib]System.Console::WriteLine(float32) IL_0027: nop //从堆栈中加载出val IL_0028: ldloc.0 //从堆栈中加载出i IL_0029: ldloc.1 //将i转换为float类型 IL_002a: conv.r4 //val*i IL_002b: mul //将乘法运算之后的结果转换为double类型 IL_002c: conv.r8 //调用Math.Floor对运算后的结果处理 IL_002d: call float64 [mscorlib]System.Math::Floor(float64) IL_0032: call void [mscorlib]System.Console::WriteLine(float64) IL_0037: nop IL_0038: ldloc.0 IL_0039: conv.r8 IL_003a: call void [mscorlib]System.Console::WriteLine(float64) IL_003f: nop IL_0040: ldloc.0 IL_0041: ldloc.1 IL_0042: conv.r4 IL_0043: mul IL_0044: conv.r8 IL_0045: call void [mscorlib]System.Console::WriteLine(float64) IL_004a: nop IL_004b: ldloc.0 IL_004c: conv.r8 IL_004d: ldloc.1 IL_004e: conv.r8 IL_004f: mul IL_0050: call void [mscorlib]System.Console::WriteLine(float64) IL_0055: nop IL_0056: call string [mscorlib]System.Console::ReadLine() IL_005b: pop IL_005c: ret } // end of method Program::Main
c# float和double的“坑”
时间: 2024-11-03 13:18:30