开发者

Does \ perform integer division in VB?

开发者 https://www.devze.com 2023-03-31 11:18 出处:网络
In VB.NET even if both the operands are integer, the / operator will cause the value to be floating point (if the result is non开发者_开发百科 integer).

In VB.NET even if both the operands are integer, the / operator will cause the value to be floating point (if the result is non开发者_开发百科 integer).

So I tried with the \ operator which yields integer value irrespective of the operands.

So I thought \ is integer division.

2.5 \ 3 results in 0.

Now I tried 1.5 \ 2. I expected it to be 0 but it resulted in a 1.

Now, is it a bug or a correct result?

What the \ operator actually is?

If it's a bug it exists right through VB6.


If you use \ on non-integers, you first convert them to integers, which causes rounding: the equivalent of CLng(1.5) \ 2, which is 2 \ 2 or 1.

If you use Option Strict On then you will see this taking place.


See the Remarks-Section in the Documentation:

Before performing the division, Visual Basic attempts to convert any floating-point numeric expression to Long. ... The conversion to Long is also subject to banker's rounding.

That means 1.5 \ 2 becomes 2 / 2 which is 1.

Banker's rounding (from Type Conversion Functions):

If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5 rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker's rounding, and its purpose is to compensate for a bias that could accumulate when adding many such numbers together.


not a bug, but simply the result is rounded to the nearest whole number. The operator / is used to make a division between numbers and integers float or double, not forgetting also the Decimal type.

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消