#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?
The multiplication assignment operator ( *= ) multiplies a variable by the value of the right operand and assigns the result to the variable.
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.
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-- .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With