有人愿意解释为什么这两段代码显示出不同的结果吗?
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
有人愿意解释为什么这两段代码显示出不同的结果吗?
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代码:
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