首页 > 解决方案 > 为什么将返回值分配给 int 时,它本身会减一?

问题描述

问题是当乘以像 9.58 这样的双精度类型数并将其存储在整数类型数中时,我得到的是 957 而不是 958。

当我分别尝试将 9.58*100 分配给程序中的整数时,它可以工作。怎么来的?

#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;
}

我已经单独检查过了,这个问题没有出现。

你能帮我吗

标签: c++precisionapproximation

解决方案


推荐阅读