View Single Post
  #4 (permalink)  
Old August 7th, 2009, 01:06 AM
Old Pedant Old Pedant is offline
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Let's take a real example.

Let's say Fahrenheit is 58 degrees.

So:

Celcius = 5 / 9 * (Fahrenheit - 32)
==>> 5 / 9 * (58 - 32)
The parens are evaluated first so that
==>> 5 / 9 * 26
Because multiplication and division have the same OPERATOR PRECEDENCE (look it up), that expression is evaluated strictly LEFT TO RIGHT:
so 5 / 9 ==>> 0 (since both 5 and 9 are integers)
and then 0 * 26 ==>> 0

**************

Now consider:
Celcius = (Farenheight - 32) * 5 / 9
==>> (58 - 32) * 5 / 9
==>> 26 * 5 / 9
Again, with multiplication and division equal in precedence, the order is left to right, so:
26 * 5 ==>> 130
130 / 9 ==>> 14 (should be 14.44444444 but remember, this is INTEGER math)

So it all comes down to the order that things are done in.

Here's a related problem for you:

What is the value of 3 + 7 * 5 ??

If you said 50, go back to elementary algebra class.

Multiplication has a higher precedence than addition, so *IT* happens first. Just as if you had coded

3 + ( 7 * 5 ) ==>> 3 + 35 ==>> 38

But, again, that doesn't apply when the two operators have equal precedence. Then it's strictly left to right.

** EXCEPTION IN C++ (and C and C# and...) **
The assignment operators (= and += and *= and so on) happen RIGHT TO LEFT.

That's why you can do

x = y = 7;
a = b += 3;

The y = 7 happens first and then the x = y. Ditto for the b += 3 going first. And then the a = b means that a and b end up with the same value.

There will be a quiz Monday. No calculators allowed.