sksingh
sksingh

Reputation: 27

I am getting different answer by doing the same calculation in different ways ( which are almost similar ) in GNU C++17

I was basically trying to find the number obtained on multiplying 2 with the quotient obtained on dividing 5e+8 with 3. I tried a couple of ways as shown in the snippet with GNU C++17 and got the correct answer only in the Approaches 2 and 4. I was first expecting it to be some sort of overflow situation however the maximum number that a signed int can store is a little more than 2e+9 which is much greater than the numbers which I was dealing with so I think that the issue might be something else. It would be great if someone could help out. Thanks in advance : )

using namespace std;

int main(){

// I basically wan't to calculate: 2 * 500000000/3 ( 2 * 5e+8 / 3)

    // Approach 1
    cout<<2 * 500000000 / 3<<"\n";  // output : 333333333 (nine 3s) WRONG!

    // Approach 2
    int a = 500000000/3;    // output : 333333332 (eight 3s) CORRECT!
    cout<<2 * a<<"\n";

    // Approach 3
    a = 2 * 500000000/3;    // output : 333333333 (nine 3s) WRONG!
    cout<<a<<"\n";

    // Approach 4 
    cout<<500000000 / 3 * 2<<"\n";  // output : 333333332 (eight 3s) CORRECT!
}

Upvotes: 0

Views: 56

Answers (2)

Ruslan
Ruslan

Reputation: 19110

Order of operations matters. When you calculate 2 * 500000000 / 3, it's equal to

floor(floor(2 * 500000000)/3)

(in the mathematical meaning of operations on real numbers), while the calculation of 2 * (500000000/3), which is your second approach, is equal to

floor(2 * floor(500000000/3)).

This is because each integer arithmetic operation is always followed by rounding towards zero (which for non-negative result is the same as floor).

Approach 3 is equivalent to 1, and approach 4 is equivalent to 2.

Upvotes: 0

gmatht
gmatht

Reputation: 835

We can verify that both the answers are in fact correct my hand.

(2*500,000,000)/3 = (1000,000,000)/3=333,333,333

and

(500,000,000/3)*2 = (166,666,666)*2 =333,333,332

This has to do with how in C++ integer division always rounds down and nothing to do with overflow. Arguably 333,333,333 is more accurate approximation of the "real" answer 333,333,333.333...

Upvotes: 2

Related Questions