Does \ perform integer division in VB?
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.
\
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
.
\
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.
精彩评论