I am trying to divide two decimals and want to get the exact integer part of the result only using a\b. Consider the following example:
Dim a, b As Integer
a = 200
b = 2
Writeline(Math.Log(a) / Math.Log(b))
Writeline(Math.Log(a) \ Math.Log(b))
On (Math.Log(a) / Math.Log(b)
I am getting 7.64385619 and I was expecting to get 7 with Math.Log(a) \ Math.Log(b)
but instead its returning 5. What should I do to return 7 instead of 5? How am I getting 5 there? When dealing with whole numbers it works fine. I tried to look on the internet but could not get a solution. Probably its my search phrasing.
This is a perfect example of why you should ALWAYS read the relevant documentation. Here is the documentation for the integer division operator. It says this:
Before performing the division, Visual Basic attempts to convert any floating-point numeric expression to Long. If Option Strict is On, a compiler error occurs. If Option Strict is Off, an OverflowException is possible if the value is outside the range of the Long Data Type. The conversion to Long is also subject to banker's rounding.
You clearly have Option Strict Off
, or else your code wouldn't even compile. That's a bad thing from the start. With Option Strict Off
in your case, 5.2983173665480363
and 0.69314718055994529
are rounded to 5
and 1
respectively. 5 \ 1
is 5, which is the result you're seeing.
What that means is that you cannot use integer division in this case. You will need to use regular division and then call Math.Floor
or Math.Truncate
to remove the fractional part.