user990808
user990808

Reputation: 11

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

# include <iostream>
using namespace std;

int main()
{
    double a;
    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?

Upvotes: 1

Views: 1334

Answers (2)

Vaughn Cato
Vaughn Cato

Reputation: 64308

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

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

Upvotes: 2

Suma
Suma

Reputation: 34423

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.

Upvotes: 5

Related Questions