Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

operators

#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?

like image 240
Danny Campise Avatar asked May 12 '13 20:05

Danny Campise


People also ask

What does *= mean in code?

The multiplication assignment operator ( *= ) multiplies a variable by the value of the right operand and assigns the result to the variable.

What is the meaning of a *= b?

so. a -= b is equivalent to a = a - b. a *= b is equivalent to a = a * b. a /= b is equivalent to a = a / b.

What is the order of precedence in evaluating the operators * ()?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .


1 Answers

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.

like image 176
Jason Avatar answered Nov 10 '22 00:11

Jason