我们要让用户在列表中输入每12个月的总降雨量。程序应该计算和显示全年的总降雨量,即月平均降雨量。
问题:最大值很好,但最小值停留在0
代码:
Rainfall=[0]*13
i=1
total=0
print("Enter the Rainfall each month")
while i<=12:
print('Month #',i, ': ',end=' ')
Rainfall[i]=float(input())
total+=Rainfall[i]
i+=1
ave=total/12
High = max (Rainfall)
Low = min(Rainfall)
print("total Amount= ",total)
print("Average Average Amount {:0.2f}".format(ave))
print ("The months with the highest value are : ")
print ([i for i, j in enumerate(Rainfall) if j == High])
print ("The months with the Lowest value are : ")
print ([i for i, j in enumerate(Rainfall) if j == Low])
output:Enter the Rainfall each month
Month # 1 : 1
Month # 2 : 1
Month # 3 : 399
Month # 4 : 900
Month # 5 : 900
Month # 6 : 900
Month # 7 : 900
Month # 8 : 2323
Month # 9 : 42
Month # 10 : 100
Month # 11 : 10000
Month # 12 : 10000
total Amount= 26466.0
Average Average Amount 2205.50
The months with the highest value are :
[11, 12]
The months with the Lowest value are :
[0]
Process finished with exit code 0
发布于 2020-04-14 14:41:05
因为循环从i=1开始,所以您没有填充列表Rainfall
中的第一个索引,但是列表的第一个索引是0(它的值是0)。
试试这个:
Rainfall=[0]*12
i=0
print("Enter the Rainfall each month")
while i<len(Rainfall):
print('Month #',i, ': ',end=' ')
Rainfall[i]=float(input())
i+=1
total = sum(Rainfall)
ave=total/len(Rainfall)
High = max (Rainfall)
Low = min(Rainfall)
print("total Amount= ",total)
print("Average Average Amount {:0.2f}".format(ave))
print ("The months with the highest value are : ")
print ([i+1 for i, j in enumerate(Rainfall) if j == High])
print ("The months with the Lowest value are : ")
print ([i+1 for i, j in enumerate(Rainfall) if j == Low])
发布于 2020-04-14 14:44:31
您的数组有13个元素(而不是12个)。数组从索引0开始,但您从1开始填充它。
降雨量始终为0
调整你的代码。变化
Rainfall=[0]*12
i=0
....
while i<12
...
print('Month #',i+1, ': ',end=' ')
...
https://stackoverflow.com/questions/61201871
复制相似问题