![](/img/trans.png)
[英]Python: Write a program that counts positive and negative numbers and computers the average of numbers
[英]Python: (Count positive and negative numbers and compute the average of numbers)
問題陳述:編寫一個程序,讀取未指定數量的整數,確定已讀取多少個正值和負值,並計算輸入值的總和和平均值(不計零)。 您的程序以輸入0結尾。將平均值顯示為浮點數。
輸出示例(忽略項目符號,不知道如何將文本格式化為控制台輸出):
嘗試的解決方案:
def main():
i = int( input ("Enter an interger, the input ends if it is 0: "))
count_pos = 0
count_neg = 0
total = 0
if (i != 0):
while (i != 0):
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
total += i
i = int( input ("Enter an interger, the input ends if it is 0: "))
count = count_pos + count_neg
average = total / count
print ("The number of positives is", count_pos)
print ("The number of negatives is", count_neg)
print ("The total is", total)
print ("The average is", float(average))
else:
print ("You didn't enter any number.")
main()
您不需要此行(這就是發生錯誤的原因):
main(i)
要持續獲取用戶輸入,請使用無限循環,然后測試打破循環的條件。
while (true):
i = input("Enter an integer (0 to stop): ")
if(i == 0)
break
sum1 += i
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
然后計算並返回平均值。
您正在使用參數“ i”調用主函數,該參數不存在。 您不能使用在該函數之外的函數中聲明的變量
檢出: Python作用域
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.