You've encountered one of the problems of dealing with floating-point values, the results are inexact.
Let's take an example using ordinary decimal numbers first.
Say you have a pocket calculator,and work out 1 / 3
The result wil be 0.33333333
Now multiply that by 3
the result is 0.99999999
Now if we take just the integer part, we get the result 0.
That is more or less what is happening in your example. Although in decimal notation 0.03 can be represented exactly, the computer works in binary, and that value becomes a recurring sequence of digits, the value stored is just an approximation (in the same way that 0.33333 is an approximation to 1/3).
So your code is probably producing a result like 2.99999999 but when you assign it to an integer, the fractional part is discarded, and you are left with just the 2.
One way to deal with this is to use variables of type double for all the calculations. Another is, if assigning to an integer, apply a rounding algorithm. For example, you might put
1 2
|
double r = 0.03;
int rr = r * 100 + 0.5; // add 0.5 for correct rounding
|