user5927645
user5927645

Reputation:

1 / 0.2 should be 5, so why is the result 4?

/* 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?

Upvotes: 1

Views: 5716

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33854

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.

Upvotes: 9

William B.
William B.

Reputation: 83

this is almost definitely a rounding error. test it for yourself ->

a = 2
b = 1
c = 0.2000000001
res = 4

i would suggest using a double instead of a float, it should provide you with the precision you need. of course, going from doubles to integers always has the risk of rounding wrong, without using some sort of rounding function to compensate

Upvotes: -2

Related Questions