This forum is now read-only. Please use our new forums! Go to forums

0 points
over 9 years

So it works, but how/why?

meal = 44.50
tax = 0.0675
tip = 0.15

meal += meal * tax

total = meal + meal * tip
print("%.2f" % total)

shouldnt

total = meal + meal * tip

be equal to (47.50375 + 47.50375 * 0.15) = 14.251125 ?

how does it work?

Also: What the hell does the last line of code do?

Answer 54a1835776b8fef4480142bf

2 votes

Permalink

Remember the order of operations. The computer follows it also.

(47.50 + 47.50 * 0.15) = (47.50 + 7.13 ) = 54.63 Because multiplication is carried out before addition.

As for %.2f, that just prints 2 decimal places of the result.

points
Submitted by narcaro
about 9 years

Answer 54a45de151b8872850000388

2 votes

Permalink

Another question. Why meal + meal? If meal is 44.50, then I would expect this to be the equivalent of 44.50 + 44.50 which would give 89.00.

points
Submitted by Keith
about 9 years

4 comments

Victor Skårerverket about 9 years

Total should be 47.50 + 47.50 * 0.15 ?

BogdanG about 9 years

Order of operations. In math u do Multiplications before the addition. So the computer does it the same way. In that line u just add the tax value to the meal value.

elgarsrevanche about 9 years

I’m still not getting why meal + meal * tax is necessary over meal * tax, any takers? I understand it’s right, just not why, which will trip me up eventually,,,

ifbatmanwasreal almost 9 years

meal * tax gives you the value of the tax (44.50 * .15 = 6.675). the extra meal is to add the value of the meal back to the bill. 6.675 + meal

Answer 54c7d8b595e378f106003443

0 votes

Permalink

total = (meal + meal* tax)+(meal + meal* tax)*tip

points
Submitted by moni24
about 9 years