Ex21 extra credit

Hi all!
I’ve been been stuck on this for a couple of days now and thought I’d reach out to LPTHW community.
I think I’ve worked the original formula out correctly, as they both return the same figure, but the problem I’m having is with my own formula. I used the same method to simplify my formula as I did with the example, however its outputting two different figures and I really can’t see why.
So my question is, what have I actually done wrong here and what am I not seeing?

For context I’m a carpenter that is trying to change his career, so please be gentle :joy:

Thank you in advance for your time and knowledge!


# Example formula.
why = add(age, subtract(height, multiply(weight, divide(iq, 2))))
what = age+height-(weight*iq/2)
print("That becomes: ", what,"Can you do it by hand?")
print("That becomes: ", why,"Can you do it by hand?")

# My formula
who = multiply(iq, add(age, subtract(weight, divide(height, 2))))
when = iq*age+(weight-height/2)
print("My formula equates: ", who, "using the same numbers as shaws.")
print("My formula equates: ", when, "using the same numbers as shaws.")
Example output:

Here is a puzzle.
DIVIDING 50.0 / 2
MULTIPLYING 180 * 25.0
SUBTRACTING 74 - 4500.0
ADDING 35 + -4426.0
That becomes:  -4391.0 Can you do it by hand?
That becomes:  -4391.0 Can you do it by hand?

my formulas output: 

SUBTRACTING 180 - 37.0
ADDING 35 + 143.0
MULTIPLYING 50.0 * 178.0
My formula equates:  8900.0 using the same numbers as shaws.
My formula equates:  1893.0 using the same numbers as shaws
1 Like

Operator precedence. * has a higher precedence than +, so the second caculation is implicitly this one:

when = (iq * age) + (weight - height/2)

Not the same as the first one. You need to use parentheses to correct this.


Thank you @florian for your response, I should have realised that as PEDMAS was taught to me at school! I appreciate your time and thank you again.

1 Like

Yes, in this case we all know it from school, but operator precedence is actually something you have to be aware of in programming in general. Most programming languages have many different operators and define their own precedence hierarchy. These are often similar, but in the end you never quite know, because nobody learns these tables by heart. When in doubt, use parentheses. :slight_smile:

1 Like

Thank you for that helpful insight I’ve made a mental and physical note of it, and due to your help I’ll be studying up on operator precedence with more depth. Your time is truly appreciated and thank you again.

1 Like