VB.NET vs C # integer division

Does anyone want to explain why these two codes have 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 
+80
operators c # division
May 16 '11 at 5:49 a.m.
source share
5 answers

When you look at the IL code generated by these two fragments, you will realize that VB.NET first converts the integer values ​​to doubles, applies division, and then rounds the result before it is converted back to int32 and stored in y.

C # does nothing.

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 

Correct integer division in VB requires a backslash: p \ i

+82
May 16 '11 at 5:56 a.m.
source share

In VB, to make an integer , reverse the slash:

 Dim y As Integer = p \ i 

otherwise, it expands to a floating point for division, and then forcibly returns to int after rounding when assigning y .

+78
May 16 '11 at 5:53
source share

VB.NET integer splitting operator is \ , not / .

+16
May 16 '11 at 5:54
source share

"A division is performed differently in C # and VB. C #, like other C-based languages, truncates the division result when both operands are integer literals or integer variables (or integer constants). In VB you must use the integer division operator ( \ ) to get a similar result.

Source

+8
May 16 '11 at 5:54 am
source share

In C #, integer division is applied with / when the numerator and denominator are integers. Whereas in VB.Net '/' is the result of floating point decomposition, so for integer division in VB.Net use \ . Look at the MSDN message .

-four
May 16 '11 at 5:57
source share



All Articles