在一行中输入多个值,并获得使用Python输入的值的平均值

2024-06-16 11:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python,我需要编写一个脚本,允许用户输入3个数字(不多也不少),然后计算输入的三个数字的平均值并打印出来

我想出了如何让用户在同一行中输入三个条目,并可以根据需要打印所有三个条目。但是因为我用的是x,y,z,我不知道如何得到平均值

x, y, z = input("avg3: ").split()
print("Average of " + (x) + ", " + (y) + " and " + (z) + " is ")
print()

Tags: andof用户脚本inputis条目数字
2条回答

您可以将它们加载到numpy数组中,并获得该数组的平均值

import numpy as np

array = np.zeros(3)
array[0] = x
array[1] = y
array[2] = z
print(np.average(array))

当您有多个值时,这尤其有用

尝试:

x, y, z = input("avg3: ").split()
print("Average of " + (x) + ", " + (y) + " and " + (z) + " is " , (int(x)+int(y)+int(z))/3)

相关问题 更多 >