我正在尝试冒泡排序温度阵列,但我得到这种错误…谁来帮我解决这个问题:)
代码如下:
print("")
print("")
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"]
temperature = []
highest = float(0.0)
lowest = float(100.0)
total = float(0.0)
for i in range(7):
inp = round(float(input("Please enter the temperature for " + days[i] + " in Celcus: ")),1)
temperature.append(inp)
print("")
print("")
print("You entered these Temperatures in Celsius and Fahrenheit.")
print("")
print("")
for j in range(len(temperature)):
def bubble_sort(tem):
for a in range(len(tem)):
for b in range(len(tem)-1):
if(tem[b]>tem[b+1]):
temp=tem[b]
tem[b]=tem[b+1]
tem[b+1]=temp
return tem
arr = []
arr.append(temperature[j])
Fahrenheit = round(((temperature[j] * 1.8) + 32),1)
total = total + temperature[j]
print(bubble_sort(arr) + " C° is " + str(Fahrenheit) + " F°" )
print("--------------------")
avg = round(total / len(temperature),1)
print("High Temp: " + str(max(temperature)) + "C°, Low Temp: " + str(min(temperature)) + " C° Average Temp: " + str(avg) + " C°")
我不明白这段代码有什么问题。
错误非常明显:list
是bubble_sort(arr)
,str
是" C° is "
你不能在bubble_sort(arr) + " C° is "
连接它们,你需要将列表包装到str
最好的是使用print
允许给定多个值的事实
print(bubble_sort(arr), "C° is", Fahrenheit, "F°")
print("High Temp:", max(temperature), "C°, Low Temp:",
min(temperature), "C° Average Temp:", avg, "C°")
现在,你没有排序任何东西因为arr
中只有一个值,所以在循环之前只排序一次,然后显示华氏温度
arr = bubble_sort(temperature)
for value in arr:
fahrenheit = round(((value * 1.8) + 32), 1)
print(value, "C° is", fahrenheit, "F°")
avg = round(sum(temperature) / len(temperature), 1)
print("High Temp:", max(temperature), "C°, Low Temp:",
min(temperature), "C° Average Temp:", avg, "C°")
缺陷线
print(bubble_sort(arr) + " C° is " + str(Fahrenheit) + " F°" )
,因为你使用了"+"列表和字符串上的操作符为了修复它,尝试转换列表(调用"bubble_sort(arr)"到一个字符串)
这样的
print(''.join(str(e) for e in bubble_sort(arr)) + " C° is " + str(Fahrenheit) + " F°")