gpt4 book ai didi

python - 我的程序不断出现错误 "division by zero"

转载 作者:行者123 更新时间:2023-11-28 21:11:22 25 4
gpt4 key购买 nike

这个程序被设计用来计算未指定数量的整数,确定已读取了多少负值和正值,并计算输入值的平均值和总和。

如果用户输入0,程序将结束。每次我输入 0 时,我都会收到一条错误消息,指出“被零除”。调试器说它来自最后一行。

我猜它必须与 sum/count 部分有关。当我使用负数时,它说同样的事情,来自同一行代码。最后,我不确定如何显示文本“您没有输入任何数字”。我尝试执行 if else 语句,但我认为我做的不正确。

data = eval(input("Enter an integer, the input ends if it is 0: "))
count = 0
sum = 0
negCount = 0
if data != 0:
while data > 0:
count = count + 1
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
while data < 0:
negCount = count + 1
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
while data != 0:
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
break
else:
print("You didn't enter any number")



print("The number of positives is", count)
print("The number of negatives is", negCount)
print("The total is", sum)
print("The average is", sum / count)

最佳答案

output = []
while True:
data = int(input("Enter an integer, the input ends if it is 0: "))
if data == 0:
break
output.append(data)

positives = len([i for i in output if i > 0])
negatives = len(output) - positives
total = sum(output)

if len(output) != 0:
print("The number of positives is", positives)
print("The number of negatives is", negatives)
print("The total is", total)
print("The average is", total / len(output))
else:
print("You didn't enter any number")

关于python - 我的程序不断出现错误 "division by zero",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35492196/

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