如何在Python中使用用户输入浮动并找到平均值、最小值、最大值和范围
我知道如何处理整数,但我不知道如何从用户那里获取浮点数并找到平均值、最小值、最大值和范围。我一直收到一条错误消息,上面写着:TypeError:“float”对象是不可编辑的 这是我到目前为止的最小代码,我知道它不起作用,但我只是在寻找有关如何获取浮点用户数并找到平均值、最小值、最大值和范围的建议。谢谢如何在Python中使用用户输入浮动并找到平均值、最小值、最大值和范围,python,Python,我知道如何处理整数,但我不知道如何从用户那里获取浮点数并找到平均值、最小值、最大值和范围。我一直收到一条错误消息,上面写着:TypeError:“float”对象是不可编辑的 这是我到目前为止的最小代码,我知道它不起作用,但我只是在寻找有关如何获取浮点用户数并找到平均值、最小值、最大值和范围的建议。谢谢 import statistics def main (): userNum= float(input("Give me 5 numbers "))
import statistics
def main ():
userNum= float(input("Give me 5 numbers "))
average = statistics.mean(userNum)
print("The average of the numbers given is: ", average)
print(max(userNum))
print(min(userNum))
main()
不能直接将输入转换为浮点。首先,您需要拆分用户输入。如果是这样的话:
"3.4, 5.6, 8.7, 6.4, 9.8"
然后试着这样做:
import statistics
def main():
userNum = float(input("Give me 5 numbers "))
userNum = [float(x) for x in userNum.split(", ")]
average = statistics.mean(userNum)
print("The average of the numbers given is: ", average)
print(max(userNum))
print(min(userNum))
main()
首先,调用函数时需要缩进
main()
函数,我指的是代码的最后一行
这是我的解决方案,没有统计
模块,因为我对它不太熟悉
def main():
tries = 0
while True:
tries += 1
print(f'try number {tries}')
user_num = float(input('Enter five floating points: '))
if tries == 1:
sum1 = user_num
elif tries == 2:
sum2 = user_num
elif tries == 3:
sum3 = user_num
elif tries == 4:
sum4 = user_num
elif tries == 5:
sum5 = user_num
sums = sum1 + sum2 + sum3 + sum4 + sum5
print(f'sum is {sums}')
average = sums / tries
print(f'The average of the numbers given is: {average}')
all_numbers = [sum1, sum2, sum3, sum4, sum5]
all_numbers.sort()
print(f'sorted: {all_numbers}')
print(f'the minimum number is {all_numbers[-1]}')
print(f'the maximum number is {all_numbers[0]}')
break
main()
我希望你喜欢
玩得开心:)更新:这就是我找到的解决方案。也许这太简单了,但对我来说很有效
def main ():
import statistics
userNum= input("Enter 5 floating point values seperated by a space")
x=[float(x) for x in userNum.split(" ")] #converts string to floating point
values
average = statistics.mean(x) #find the average value entered
print("The average of the numbers given is: ", average) #print the average
number entered
print (min(x), "The min number given") #print the min number entered
print (max(x), "The max number given") #print the max number entered
diff= max(x) - min(x) #calculate the range
print (diff, "This is the range of numbers given") #print the range
main()
尝试userNum=[float(x)代表输入中的x(“给我5个数字”).split()]