在c ++中修复static_cast <int>()的精度

1 c++ floating-point precision

# include <iostream>
using namespace std;

int main()
{
    double a;
    cin >> a;
    int b = (int) a*100;
    cout << b << endl;
}
Run Code Online (Sandbox Code Playgroud)

如果输入2.53,则给出b = 252

我知道这是一个精确的事情,但是如何在不使用比较的情况下修复它?

Sum*_*uma 5

如果a保证为正数,请使用:

int b = (int) (a*100+0.5);
Run Code Online (Sandbox Code Playgroud)

如果不使用:

int b = (int) floor(a*100+0.5);
Run Code Online (Sandbox Code Playgroud)

浮点到int cast truncates(向零舍入).

如果要继续截断,但只想避免精度问题,请在上面的代码中使用小epsilon(1e-4)而不是0.5 int.