相关疑难解决方法(0)

在C#中将float转换为int时的奇怪行为

我有以下简单的代码:

int speed1 = (int)(6.2f * 10);
float tmp = 6.2f * 10;
int speed2 = (int)tmp;
Run Code Online (Sandbox Code Playgroud)

speed1和speed2应该具有相同的值,但事实上,我有:

speed1 = 61
speed2 = 62
Run Code Online (Sandbox Code Playgroud)

我知道我应该使用Math.Round而不是cast,但我想了解为什么值不同.

我查看了生成的字节码,但除了存储和加载外,操作码是相同的.

我也在java中尝试了相同的代码,我正确地获得了62和62.

有人可以解释一下吗?

编辑: 在实际代码中,它不是直接6.2f*10而是函数调用*常量.我有以下字节码:

速度1:

IL_01b3:  ldloc.s    V_8
IL_01b5:  callvirt   instance float32 myPackage.MyClass::getSpeed()
IL_01ba:  ldc.r4     10.
IL_01bf:  mul
IL_01c0:  conv.i4
IL_01c1:  stloc.s    V_9
Run Code Online (Sandbox Code Playgroud)

速度2:

IL_01c3:  ldloc.s    V_8
IL_01c5:  callvirt   instance float32 myPackage.MyClass::getSpeed()
IL_01ca:  ldc.r4     10.
IL_01cf:  mul
IL_01d0:  stloc.s    V_10
IL_01d2:  ldloc.s    V_10
IL_01d4:  conv.i4
IL_01d5:  stloc.s    V_11
Run Code Online (Sandbox Code Playgroud)

我们可以看到操作数是浮点数,唯一的区别是stloc/ldloc

至于虚拟机,我尝试使用Mono/Win7,Mono/MacOS和.NET/Windows,结果相同

c# floating-point int expression casting

127
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×1

casting ×1

expression ×1

floating-point ×1

int ×1