VB.NET对C#整数除法除法、整数、VB、NET

2023-09-04 00:04:17 作者:得不到也忘不掉

有人在乎解释为什么这两件code表现出不同的结果?

VB.NET V4.0

 昏暗数p作为整数= 16
昏暗我为整数= 10
昏暗y为整数= P / I
//结果:2
 

C#4.0版

  INT P = 16;
INT I = 10;
INT Y = P / I;
//结果:1
 

解决方案 VB积最大的整数分解

当你看看IL-code这两个片段产生,你就会意识到,VB.NET首先将整数值双打,应用划分,然后舍入结果之前,它的转换回INT32并存储在年。

C#确实没有了。

VB.NET IL code:

  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:拨打System.Math.Round
IL_0010:conv.ovf.i4
IL_0011:stloc.2
IL_0012:ldloc.2
IL_0013:打电话的System.Console.WriteLine
 

C#IL code:

  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:打电话的System.Console.WriteLine
 

在VB中的正确的整数除法需要向后斜线:P \我

Anyone care to explain why these two pieces of code exhibit different results?

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

解决方案

When you look at the IL-code that those two snippets produce, you'll realize that VB.NET first converts the integer values to doubles, applies the division and then rounds the result before it's converted back to int32 and stored in y.

C# does none of that.

VB.NET IL Code:

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 Code:

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

The "proper" integer division in VB needs a backwards slash: p \ i