Danny Campise
Danny Campise

Reputation: 133

Why is the *= operator not functioning the way I would expect it to?

#include <iostream>
using namespace std;

int main ()
{
    //If a triangle has a perimeter of 9 units, how many iterations(each iteration is 4/3 as much) would it take to obtain a perimeter of 100 units? (or as close to 100 as you can get?)
    double p = 9; int it = 0;
    for(p; p < 100; p = p * 4/3){
        cout << p << endl;
        it++;
    }
    cout << p << endl;
    cout << it << endl;
    system ("PAUSE");
    return 0;
}

So for a math project I was doing, I had to figure out how many iterations it would take for a perimeter of 9 to reach 100 if you increase the perimeter 4/3x as much during each iteration. When I write the code like I do above, the output is fine, however if I change

for(p; p < 100; p = p * 4/3)

to

for(p; p < 100; p *= 4/3)

I get output that doesn't make sense. Am I misunderstanding the *= operator? Do I need parentheses somewhere?

Upvotes: 13

Views: 546

Answers (1)

Jason
Jason

Reputation: 13986

It's the order of operation. In p = p * 4/3 the compiler is doing:

p = (p * 4)/3

However in p *= 4/3, the compiler is doing:

p = p * (4/3)

4/3 is 1 on the computer because of integer division, so the second example is basically multiplying by 1.

Instead of dividing by 3 (an integer), divide by 3.0 (a double) or 3.0f (a float). Then p *= 4/3.0 and p = p * 4/3.0 are the same.

Upvotes: 28

Related Questions