c#语言float转换int,C#Float表达式:将结果float转换为int时的奇怪行为
我有以下簡單代碼:
int speed1 = (int)(6.2f * 10);
float tmp = 6.2f * 10;
int speed2 = (int)tmp;
speed1并且speed2應(yīng)該具有相同的值,但實(shí)際上,我有:
speed1 = 61
speed2 = 62
我知道我可能應(yīng)該使用Math.Round而不是強(qiáng)制轉(zhuǎn)換,但是我想了解為什么值不同。
我查看了生成的字節(jié)碼,但是除了存儲和加載之外,操作碼是相同的。
我也在Java中嘗試了相同的代碼,并且正確獲得了62和62。
有人可以解釋嗎?
編輯: 在實(shí)際代碼中,它不是直接6.2f * 10,而是函數(shù)調(diào)用*常量。我有以下字節(jié)碼:
為speed1:
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
為speed2:
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
我們可以看到操作數(shù)是浮點(diǎn)數(shù),唯一的區(qū)別是stloc/ldloc。
至于虛擬機(jī),我嘗試使用Mono / Win7,Mono / MacOS和.NET / Windows,結(jié)果相同。
總結(jié)
以上是生活随笔為你收集整理的c#语言float转换int,C#Float表达式:将结果float转换为int时的奇怪行为的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python排名分析_用Python分析
- 下一篇: window上安装mysql服务核心版(