C++ – Why Does 1 / 0.2 Result in 4 Instead of 5?

c++floating-point

/* I am currently learning c++ as part of my core subjects */

Strangely, while writing another long program i ran into this instance

#include <iostream>
#include <cmath>
using namespace std;  
int main()
  {
    int a,b,res; float c;
    cin>>a;
    cin>>b;
    cin>>c;
    res=(a-b)/c;
    cout<<res;
  }

Input :

a = 2 b = 1 c = 0.2

Output :

4

Desired Output :

5

I need to find res, (the number of steps of increment c) in between the starting a and end b truncated to the closest floor integer value.

I tried defining (a-b) as another int, still same result 4 instead of 5.

But simply testing

int main()
{
    cout<<(2-1)/0.2;
}

correctly gave 5.

One more doubt: if I do not define any variable, like above, what datatype will the system assume for the result?

Best Answer

You have the age old problem of rounding floats which stems from the fact that floating point numbers are base 2 and therefore cannot represent all base 10 numbers perfectly (eg. 0.3). Read this tutorial and this SO question for more information.

As for your example try adding this to your program:

cout << std::setprecision(16) << (float)(a-b)/c << endl;

You will get this print out:

4.999999925494195

And what is (int)4.9999...? It is 4.

Live example.