The instructions are to assign avg_owls with the average owls per zoo. Print avg_owls as an integer. However, the math keeps coming up wrong with the sample inputs. Even when I do the math by hand. The code is as follows.
Given sample inputs are 1 2 4
avg_owls = 0.0
num_owls_zooA = int(input())
num_owls_zooB = int(input())
num_owls_zooC = int(input())
avg_owls = int(num_owls_zooA + num_owls_zooB + num_owls_zooC / 3)
print('Average owls per zoo:', int(avg_owls))
Your output Average owls per zoo: 4 Expected output Average owls per zoo: 2
I have written and can only alter the code avg_owls = int(num_owls_zooA + num_owls_zooB + num_owls_zooC / 3)
I don't understand how it's coming up with 4 when the actual math comes out to 2.333
What am I doing wrong?
Operator precedence, and the rules of maths, say that
num_owls_zooA + num_owls_zooB + num_owls_zooC / 3
will be calculated as
num_owls_zooA + num_owls_zooB + (num_owls_zooC / 3)
You need some brackets to get the result you want:
(num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3
As an extra note, applying int
to the result feels potentially wrong. It will cause it to always round down. For an average you would usually want to either keep it as a floating point value or at least round to the nearest value rather than always down.
Two problems here. In pemdas or germdas, division comes before addition. SO you need parentheses around the addition. Also if you do int(4.3)
you will get 4
. float will give you your desired output
avg_owls = 0.0
num_owls_zooA = float(input())
num_owls_zooB = float(input())
num_owls_zooC = float(input())
avg_owls = (num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3
print(f'Average owls per zoo: {avg_owls} ')
also I suggest using f strings
.
Change to:
avg_owls = int((num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3)
This solution works as tested.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.