gpt4 book ai didi

python - 类型错误 : Can't convert 'int' object to str implicitly/Sorting Array issue

转载 作者:行者123 更新时间:2023-11-30 22:37:52 26 4
gpt4 key购买 nike

代码的某个部分存在问题(我是编码新手,并尝试通过 StackOverflow 寻求帮助):

def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1

return totalRain

类型错误:无法将“int”对象隐式转换为 str

我尝试了多种方法来更改代码以使其显式成为字符串,因为它仍然给我带来了各种问题。

我也很难增强代码以升序对数组进行排序并显示它包含的值。

完整代码在这里:

def main ():
rainfall = rainInput ()
totalRain = totalRainfall (rainfall)
average_Rainfall = averageRainfall (totalRain)
highestMonth, highestMonthly = highestMonthNumber (rainfall)
lowestMonth, lowestMonthly = lowestMonthNumber (rainfall)
print #this is for spacing output
print ('The total rainfall for the year was: ' +str(totalRain) + ' inche(s)')
print #this is for spacing output
print ('The average rainfall for the year was: ' +str(average_Rainfall) +\
' inche(s)')
print #this is for spacing in output
print ('The highest amount of rain was', highestMonthly, 'in' , highestMonth)
print #this is for spacing in output
print ('The lowest amount of rain was', lowestMonthly, 'in' , lowestMonth)

def rainInput ():
rainfall = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
month = 0
while month < len(rainfall):
rainfall[month] = input ('Please enter the amount for month ' + str\
(month + 1) + ': ')
month += 1

return rainfall

def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1

return totalRain

def averageRainfall (totalRain):
average_Rainfall = totalRain / 12

return average_Rainfall

def highestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
highestMonthly = 0
for m, n in enumerate(rainfall):
if n > highestMonthly:
highestMonthly = n
highestMonth = m

return month[highestMonth], highestMonthly

def lowestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
lowestMonthly = 0
for m, n in enumerate(rainfall):
if n < lowestMonthly:
lowestMonthly = n
lowestMonth = m

return month[lowestMonth], lowestMonthly

main()

最佳答案

您的降雨量数组中存储了字符串,您需要在添加之前将它们转换为整数。

def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = int(rainfall[month]) + totalRain
month += 1

return totalRain

关于python - 类型错误 : Can't convert 'int' object to str implicitly/Sorting Array issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43747198/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com