有人可以解释一下为什么这两个代码片段表现出不同的结果吗?
VB.NET v4.0
Dim p As Integer = 16
Dim i As Integer = 10
Dim y As Integer = p / i
//Result: 2
C# v4.0
int p = 16;
int i = 10;
int y = p / i;
//Result: 1
当您查看这两个代码片段所生成的IL代码时,您会意识到VB.NET首先将整数值转换为双精度浮点数,应用除法,然后在它被转换回Int32并存储在y中之前四舍五入结果。
C#则不这样做。
VB.NET的IL代码:
IL_0000: ldc.i4.s 10
IL_0002: stloc.1
IL_0003: ldc.i4.s 0A
IL_0005: stloc.0
IL_0006: ldloc.1
IL_0007: conv.r8
IL_0008: ldloc.0
IL_0009: conv.r8
IL_000A: div
IL_000B: call System.Math.Round
IL_0010: conv.ovf.i4
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: call System.Console.WriteLine
C# 中间语言代码:
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldc.i4.s 0A
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: div
IL_0009: stloc.2
IL_000A: ldloc.2
IL_000B: call System.Console.WriteLine
在VB中,进行"正常的"整数除法需要使用反斜杠:p \ i。
在VB中,要进行整数除法,需要反斜杠:
Dim y As Integer = p \ i
否则在进行除法运算时将被转换为浮点数,然后在赋值给y前四舍五入并强制转换为整型。
"在 C# 和 VB 中,除法的执行方式不同。与其他基于 C 的语言一样,当两个操作数都是整数字面值、整数变量(或整数常量)时,C# 会截断除法结果。在 VB 中,您必须使用整数除法运算符 (\
) 才能获得类似的结果。"
p
和i
进行除法运算p / i
的结果是一个双精度浮点数Double
,然后被转换为整数类型Integer
。参考链接:https://dev59.com/pHI-5IYBdhLWcg3wPFx2。 - BoltClock