user2472706 - 2 months ago 22

Vb.net Question

When two variables are declared as integer type and you perform

14/4, you get 4, but when you use integer division, 14\4, you get 3.

I thought when you use integer division it rounds to the closest even number. So 14\4 = 3.5 (4 is the closest even number) should be 4 instead,

right?

Answer

When you cast a floating point number to an integer in VB.NET, the value is rounded to the nearest even number. Apparently rounding a number when converting it to an integer is a behavior that stretches back to the days of the BASIC language.

However, when performing integer division (with the `\`

operator), the fractional part is simply discarded, no matter what the fractional part is. This is why you get the behavior that you are seeing.

Source (Stackoverflow)

Comments