0

The problem is that when multiplying a double type number like 9.58 and storing it in a integer type number, I get 957 instead of 958.

When I separately try to assign 9.58*100 to an integer in a program, it works. How come?

#include <bits/stdc++.h>
using namespace std;
double roundit(double x)
{
    double e = x * 100;
    e += 0.5;
    cout << "func" << e << endl;
    int d = e;
    cout << "func" << d << endl;
    e = (float(d)) / 100;
    cout << "func" << e << endl;
    return e;
}
int main()
{
    int t;
    cin >> t;

    while (t--) {
        double a, b, c, d;

        cin >> a >> b >> c >> d;
        /*
    say give 
    3
    1.0 1.0 1.0 10.45
    1.0 1.0 1.0 10.44
    1.0 1.0 0.9 10.44
    as input
    */

        double ans = a * b * c * d;

        ans = 100 / ans;

        cout << ans << endl;
        ans = roundit(ans);
        cout << "main" << ans << endl; //this part right here
        int x = (ans * 100.0); //say instead of giving 9.58*100 =958, it gives 957
        cout << "main" << x << endl;
        cout << (x >= 958 ? "NO" : "YES") << endl;
    }
    return 0;
}

i've checked this separately and this problem doesn't appear.

Can you help

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 1
    Maybe the value was not 9.58 but a little lower. After increasing the precision I got `func9.57999992` which when multiplied by 100 and converted to int will be 957. – drescherjm Apr 02 '21 at 16:21
  • Chances are that `9.58` was really more like `9.579999999999`, or the result of `9.58*100` was more like `957.99999999999`. Assigning a `float`/`double` to an `int` merely truncates off the decimal portion. – Remy Lebeau Apr 02 '21 at 16:26
  • See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Apr 02 '21 at 18:58
  • The value 9.58 cannot be represented exactly in a binary floating point number. Inside a `float`, the closest value is `9.5799999237060546875`, which is slightly below 9.58. Inside a `double`, the closest value is `9.5800000000000000710542735760100185871124275` which is a pee bigger. – prapin Apr 02 '21 at 19:05

0 Answers0