2016-09-27 148 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个月使得总平均公式正确 –