Reputation: 949
The following code outputs "3". I was expecting "1".
echo $resultado."\n"; // show 2
$valor = $resultado * ($resultado - 1 / 2);
echo $valor."\n"; // show 3, and should be 1
Why does this happen?
Upvotes: 0
Views: 52
Reputation: 12804
2*(2-1/2)
The dividing operator has higher order operator precedence than the minus sign, so the computer will calculate it like this: 2*(2-(1/2)) = 2 * 1.5 = 3
Use parentheses liberally.
Upvotes: 0
Reputation: 3815
The / takes precedence over + or - To get 1 as a result you need to use
$resultado * (($resultado - 1) / 2)
Upvotes: 1
Reputation: 88647
Change it to:
echo $resultado."\n";
$valor = $resultado * (($resultado - 1) / 2);
echo $valor."\n";
You were effectively doing 2 * (2 - (1 / 2)
= 2 * 1.5
= 3
Upvotes: 0
Reputation: 5782
Because the division 1 / 2
takes precedence in the order of operations. So you have really have this expression:
$resultado * ($resaltudo - (1 / 2))
You should add parenthesis to be:
$resultado * (($resaltudo - 1) / 2)
to get the answer you want.
Upvotes: 3
Reputation: 3181
That's because the division operator (/
) has a higher precedence than the subtraction operator (-
).
Your expression becomes, in order:
1 / 2 = 0.5 // Executed first since it's the highest precedence operation inside ()
$resultado - 0.5 = 1.5 // Still in the ()
$resultado * 1.5 = 3 // Final result
To correct your expression, insert parethesis around the subtraction, like this:
$resultado * (($resultado - 1) / 2);
Upvotes: 1
Reputation: 324620
Replacing $resultado
in the expression, you get:
$valor = 2 * (2 - 1 / 2);
2 - 1 / 2 = 1.5
2 * 1.5 = 3
My suggestion is review basic math ;)
Upvotes: 0
Reputation: 22152
No, you're wrong. The / has priority on - and so your line is like:
$valor = $resultado * ($resultado - (1 / 2));
and that is:
$valor = 2 * (2 - 0.5); // and so $valor = 3
Upvotes: 1