简体   繁体   English

如何分配平均值并打印为 integer

[英]How to assign the average and print as an integer

The instructions are to assign avg_owls with the average owls per zoo.说明是为 avg_owls 分配每个动物园的平均猫头鹰。 Print avg_owls as an integer.将 avg_owls 打印为 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给定样本输入为 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您的 output 每个动物园的平均猫头鹰数:4 预期 output 每个动物园的平均猫头鹰数:2

I have written and can only alter the code avg_owls = int(num_owls_zooA + num_owls_zooB + num_owls_zooC / 3)我已经编写并且只能更改代码 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我不明白当实际数学结果为 2.333 时它是如何得出 4 的

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.作为额外说明,将int应用于结果感觉可能是错误的。 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.在 pemdas 或 gemdas 中,除法先于加法。 SO you need parentheses around the addition.所以你需要加法的括号。 Also if you do int(4.3) you will get 4 .此外,如果您执行int(4.3)您将获得4 float will give you your desired output float 会给你你想要的 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 .我也建议使用f strings

Change to:改成:

avg_owls = int((num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3) avg_owls = int((num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3)

This solution works as tested.此解决方案按测试工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM