fixing precision of static_cast<int>() in c++
# 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);
精彩评论