aman Verma
aman Verma

Reputation: 133

automatic rounding off a during typecasting in c++

I did something like this

long double n;

cin >> n;

n = n * 10000;

long long int temp = (long long) n;

now when i try to print temp, then a problem occours in some test cases like 2.36

for 2.36 the value of temp should be 23600 but the value of temp comes out to be 23599

Pls someone help me out with this already got 4 wrong ans for this.. small problem

for simplification .. my code goes like this

int main()

{

int t;

for(scanf("%d", &t); t-- ;) {

    float n;
    scanf("%f", &n);
    n *= 10000;
    long int as = (long int) n;
   cout << "\nas : " << as << " n : " << n << endl;
    long  a, b;
    a = as;
    b = 10000;
    while(a%b != 0) {
        long  temp = a % b;
        a = b;
        b = temp;
    }
    long  factor = b;
    cout << (10000/factor) << endl;
}
return 0;

}

the aim of this program was something that .. i was given a number that can have at max 4 places after the decimal. that was the average score scored by a batsman so we had to find the minimum number of matches he should play to get that score

Upvotes: 1

Views: 242

Answers (1)

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46778

This is because of the way floating-points are represented internally. You should round them off before performing truncation.

Doing a floor(n+0.5) or a ceil(x-0.5) would round the number correctly.

EDIT:

As your truncation step is a floor(..) operation in itself, you should just do n = n * 10000 + 0.5 as @Mooing Duck stated.

(Example)

Upvotes: 4

Related Questions