[英]I can't seem to figure out how to display something through nested loops
我幾乎完成了一個學校課程,但是我無法弄清楚還需要什么。 這是問題所在:
編寫一個使用嵌套循環收集數據並計算幾年內平均降雨量的程序。 該程序應首先詢問年數。 外部循環每年重復一次。 內循環將迭代十二次,每月一次。 內循環的每次迭代都會向用戶詢問該月的降雨英寸數。 在所有迭代之后,程序應顯示月份數,降雨量的總英寸數以及整個時期的每月平均降雨量。
我使用第一個循環進行每年的迭代,然后使用第二個循環進行每月的迭代(即12)。在月循環中,我詢問有多少英寸的降雨,並使每次迭代等於TotalYearlyRainfall,以便將其相加到變量。 我創建一個名為grandTotal的新變量,使其等於TotalYearlyRainfall。
for xxx in range(1,13):
這是我要在表中執行的第三個循環,我將xxx變量設置為可計算每次迭代的變量,以顯示在左欄中的每個月。
print (xxx," ",Rainfall(xx))
我不確定該如何處理第二個區域,以顯示用戶每月在第二個循環中輸入的內容。 在這一點上,我真的只是在猜測要放什么,看看是否可行。
這是我的源代碼:
Years = int(input("Enter the number of years.")) #Based on user input, the loop will iterate 'Years' times.
TotalYearlyRainfall = 0 #define properly
grandTotal = 0 #define properly
for x in range(1,Years+1): #How many years
for xx in range(1,13): #The months in each
Rainfall = int(input(("How many inches of rainfall for month ",xx,"/12?")))
TotalYearlyRainfall += Rainfall #T.Y.R is equal to Rainfall, as it adds each Rainfall.
grandTotal = TotalYearlyRainfall
#print (TotalYearlyRainfall)
print ("Months Rainfall(in)") #Table
print ("-------------------------") #Table
for xxx in range(1,13): #months
print (xxx," ",Rainfall(xx)) #I am stuck on this line...
print ("-------------------------") #Table
print ("Total Rainfall: ",grandTotal) #prints the grandTotal
Average = grandTotal / xx
print ("Average(in): ",Average) #Average amount of rainfall per month
'''
if 1-12 inputted for each
consecutive month,
Total: 78 inches.
Average: 6.5 inches.
'''
提前致謝!
在所有迭代之后,程序應顯示月份數,降雨量的總英寸數以及整個時期的每月平均降雨量。
因此,您真正需要做的就是打印三個數字:
但是,您需要稍微修改一下代碼,因為目前每個月之后您的總計被覆蓋,並且要求年數時括號太多。 您也完全不需要年度總降雨量! 嘗試:
Years = int(input("Enter the number of years: ")) #Based on user input, the loop will iterate 'Years' times.
grandTotal = 0 #define properly
for x in range(1,Years+1): #How many years
for xx in range(1,13): #The months in each
Rainfall = int(input("How many inches of rainfall for month "+str(xx)+"/12: "))
grandTotal += Rainfall #add that months rainfall to the total
Months = Years*12 #works out the number of months
Average = grandTotal/(Years*12) #works out the average
print ("Number of months (months): ", Months) #prints the total number of months
print ("Total Rainfall (in): ",grandTotal) #prints the grandTotal
print ("Average Rainfall (in per month): ",Average) #Average amount of rainfall per month
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.