Decimal multiplication with variables

So for some very odd reason, if I want to make a variable that holds (.03*100) it equals 2, which is wrong; however, if I simply print out (.03*100) it comes out as 3, which is right. I don't need an answer because I'm having a programming issue, I'm just curious as to why I'm getting two different answers?

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cmath>

int main() {
    double r = 0.03;
    int rr = r * 100;

    std::cout << rr << std::endl;;
    std::cout << r * 100;
    return 0;
}


I found out if I make int rr -> double rr it works just fine, but why can't I use int rr, because int handles whole numbers and when (.03 * 100) multiply it equals a whole number.
Last edited on
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 

Topic archived. No new replies allowed.