簡體   English   中英

Python :(計算正數和負數並計算數字的平均值)

[英]Python: (Count positive and negative numbers and compute the average of numbers)

問題陳述:編寫一個程序,讀取未指定數量的整數,確定已讀取多少個正值和負值,並計算輸入值的總和和平均值(不計零)。 您的程序以輸入0結尾。將平均值顯示為浮點數。

輸出示例(忽略項目符號,不知道如何將文本格式化為控制台輸出):

  • 輸入一個整數,如果它是0:1,則輸入結束
  • 輸入一個整數,如果輸入為0,則輸入結束:2
  • 輸入一個整數,如果為0,則輸入結束:-1
  • 輸入一個整數,如果輸入為0,則輸入結束:3
  • 輸入一個整數,如果它是0:0,則輸入結束
  • 您沒有輸入任何數字
  • 正數是3
  • 負數為1
  • 總數是5
  • 平均值是1.25

嘗試的解決方案:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM