开发者

fixing precision of static_cast<int>() in c++

开发者 https://www.devze.com 2023-04-12 04:53 出处:网络
# include <iostream> using namespace std; int main() { double a;开发者_StackOverflow中文版 cin >> a;
# include <iostream>
using namespace std;

int main()
{
    double a;开发者_StackOverflow中文版
    cin >> a;
    int b = (int) a*100;
    cout << b << endl;
}

If you input 2.53, it gives b=252

I know it's a precision thing, but how do you fix it without using comparison?


If a is guaranteed to be positive, use:

int b = (int) (a*100+0.5);

If not use:

int b = (int) floor(a*100+0.5);

Float to int cast truncates (rounds towards zero).

If you want to keep truncating, but only want to avoid precision issues, use a small epsilon (1e-4) instead of 0.5 int the code above.


You want to round instead of truncating. The floor function is handy for this:

int b = (int)floor(a*100+0.5);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号