嗨,我正在尝试创建一个程序,该程序要求数字在末尾求平均值,并在输入空格时给出平均值。我的代码如下:
number_of_numbers = 0
sum_of_numbers = 0
zero_number = 0
while number_of_numbers > -1:
decimal_number = input('Input a number: ')
if decimal_number == (''):
decimal_number = zero_number
else:
decimal_number = float(decimal_number)
number_of_numbers = number_of_numbers + 1
sum_of_numbers = sum_of_numbers + decimal_number
if decimal_number == '':
break
print((sum_of_numbers + zero_number) / number_of_numbers)
但它总是说空白是一个字符串。我试图通过为空白分配一个新变量来解决该问题,该变量算作零,但由于某种原因,我一直收到错误消息。出于某种原因,它也使我被0除。
任何帮助将不胜感激 谢谢
答案 0 :(得分:1)
将break
语句放在第一个if
中,并使用if not decimal_number:
而不是检查''
,因为空字符串是虚假的,因此在布尔上下文中它们被认为是错误的
还要在尝试除法之前检查number_of_numbers
是否为0
。
number_of_numbers = 0
sum_of_numbers = 0
zero_number = 0
while number_of_numbers > -1:
decimal_number = input('Input a number: ')
if not decimal_number:
decimal_number = zero_number
## number_of_numbers = 1
break
else:
decimal_number = float(decimal_number)
number_of_numbers = number_of_numbers + 1
sum_of_numbers = sum_of_numbers + decimal_number
if number_of_numbers == 0:
print('Cannot Divide by zero!')
else:
print((sum_of_numbers + zero_number) / number_of_numbers)
答案 1 :(得分:0)
当您碰到空白处时,您正试图停止。那是' '
,而不是''
。您正在测试''
,这不是一个空格,它只是一个长度为0的字符串。
更好的解决方案是从输入中剥离所有空格,然后然后检查其后是否为空字符串(例如,除了空格之外,什么都没有)。您将替换行
if decimal_number == (''):
使用
if decimal_number.strip() == (''):
.strip()
方法只是从字符串的前面和后面删除空格。
答案 2 :(得分:0)
我不确定在输入空格''时是否要增加number_of_numbers个数字(您可以在代码中执行此操作)。这就是为什么我提供两个版本。
1)在空白处增加number_of_numbers:
number_of_numbers = 0
sum_of_numbers = 0
while True:
decimal_number = input('Input a number: ')
if decimal_number == '':
number_of_numbers += 1
break
try:
sum_of_numbers += float(decimal_number)
number_of_numbers += 1
except ValueError:
print('Wrong Input. Try Again')
continue
print(sum_of_numbers / number_of_numbers)
2)不要在空白处增加number_of_numbers(需要检查sum_of_numbers中的零):
number_of_numbers = 0
sum_of_numbers = 0
while True:
decimal_number = input('Input a number: ')
if decimal_number == '':
break
try:
sum_of_numbers += float(decimal_number)
number_of_numbers += 1
except ValueError:
print('Wrong Input. Try Again')
continue
if number_of_numbers == 0:
print('No values to compute Average')
else:
print(sum_of_numbers / number_of_numbers)
希望有帮助。