2016-09-27 150 views
1

有幾個輸出問題與我的嵌套循環,通常我用break一些行添加到我的代碼或print()有python的輸出問題;循環總數和平均數

當我在我的代碼中使用print()我的輸出看起來像我打字上總計新行在一起,這是不是我想要的

以下是我的當前輸出和我需要一個空行的圖片;

enter image description here

第二件事:

我的代碼沒有被正確計算的信息找到每月總平均降雨量。

代碼如下

def main(): 

#define accumulators 
monthRain = 0 
year = 0 
monthTotal = 0 
months = 0 
total = 0 

#get # of years 
year = int(input("Enter the number of years to collect data for: ")) 

#blank line 
print() 

#define month total befor it is changed below with year + 1 
monthTotal = year * 12 

#define how many months per year 
months = 12 

#Find average rainfall per month 
for year in range(year): 
    #accumulator for rain per month 
    total = 0 
    #get rainfall per month 
    print('Next you will enter 12 months of rainfall data for year', year + 1) 
    for month in range(months): 
     print("Enter the rainfall for month", month + 1, end='') 
     monthRain = float(input(': ')) 

     #add monthly raingfall to accumulator 
     total += monthRain 
     average = total/monthTotal 

#total months of data 
print('You have entered data for', monthTotal,'months') 

#blank line 
print() 

#total rainfall 
print('The total rainfall for the collected months is:', total) 
print('The average monthly rainfall for the collected months is:', average) 


main() 
+0

您正在循環使用數年和數月。你想每年的總計和月平均超過1年?或者是所有年份的總數以及所有年份的月平均值?正確的答案取決於知道你想要做什麼。不清楚。 –

+0

基於用戶輸入多年的所有月份的總和平均值爲 –

回答

0

以下是我的電流輸出的圖片,我需要一個空行

爲了You have entered data for之前得到一個空行,加\n在字符串的開頭。它代表着新的一行。因此,您的打印語句應該是:

print("\nYou have entered data for") 

我的代碼沒有被正確計算的信息找到每月總平均降雨量。

在除以2個int值,蟒返回int作爲默認排除float精度。爲了得到float的值,將分子或denomenator的任何一個轉到float。例如:

>>> 1/5 
0 # <-- Ignored float value as between two int 
>>> 1/float(5) 
0.2 #<-- Float value to conversion of denomenator to float 

此外,在average = total/monthTotal,我相信average是需要每月的基礎。它應該是month而不是monthTotal。因爲total將會有month個月的降雨總和。爲了得到month個月的平均降雨量,您的公式應該爲:

average = total/float(month) 
+0

您對Python中的整數除法的評論僅適用於Python 2.'''1/5 = 0.2'''在Python 3中。要將整數除法返回Python 3你必須做''1/5 = 0''' –

+0

\ n工作(謝謝) 所收集的月份的總降雨量是:<這是我越來越亂它的地方當實際總數是67時計算64?爲第一年和總共131兩年..... 如何將兩年一起添加到一個? 所收集月份的平均月降雨量爲:「這是根據用戶輸入年份計算的總降雨量超過24個月/除以月份#......所以如果是」2年「那麼輸入那將是總降雨量/ 24個月使得總平均公式正確 –