我一直试图在过去几周内完成这项工作,而且我一直在搞乱我的代码,但我所做的一切似乎都没有帮助。我在编制总降雨量,平均降雨量和检查是否有超过12天的干旱和超过5天的洪水,雨水等于至少6英寸时遇到了问题。请帮我。我在Python 3.3中这样做。我正在模拟108天,然后一个世纪。我真的很感激一些帮助。当我运行这个程序时,我得到一个totalRain的数字,但不是降雨加起来的。对于洪水,我想使用if部分的洪水部分,但我不知道如何。对于干旱,我需要证明是否有一场12天或更长时间没有下雨的干旱。
import random
import math
def rainFallAmount(x):
if chance<=0.71:
rainfall=0;
elif chance<=0.78:
rainfall=0.5;
elif chance<=0.85:
rainfall=0.75;
elif chance<=0.92:
rainfall=1.0;
elif chance<=0.98:
rainfall=1.5;
else:
rainfall=2.0;
return rainfall;
totalRain = 0;
day=109;
num_days_no_rain = 0; # max_days_without_rain
days_of_drought = 0; # days_not_raining
days_over15 = 0;
days_rained = 0;
years = 100;
#last_5_days = [0, 0, 0, 0, 0];
days = 36500;
max_drought = 0;
#This for loop is for 108 days.
for day in range(109):
chance=random.uniform(0,1);
rainfall=rainFallAmount(chance);
print(rainfall);
#last_5_days=[day%5];
#last_5_days= rainfall;
#math.fsum([last_5_days]) > 6
#there was a flood
if rainfall<0.5:
days_of_drought+=1;
days_rained=0;
num_days_no_rain+=1;
if days_of_drought>max_drought:
max_drought=days_of_drought;
else:
days_rained+=1;
if rainfall>=1.5:
days_over15+=1;
if rainfall>=0.5:
totalRain+=1;
avgRain=totalRain/day;
print(rainfall);
print("The number of days the rain was greater than 1.5 inches: ", days_over15);
print("The longest period of no rain is: ", num_days_no_rain);
print("The total rain for", day, "days is:", totalRain);
print("The average rain per day is: ", avgRain);
print("The longest period of rain is: ", days_rained);
print("Longest drought was: ", days_of_drought,"days");
#This for loop is for a whole century.
for years in range(36500):
chance=random.uniform(0,1);
rainfall =rainFallAmount(chance);
print(rainfall);
if rainfall == 0:
days_of_drought+=1;
days_rained=0;
if days_of_drought>max_drought:
max_drought=days_of_drought;
days_rained+=1
if rainfall>=0.5:
totalRain+=1;
avgDayRain=(totalRain/day;)
avgYearRain=(totalRain/years);
print("The longest period of no rain is: ", noRain);
print("The total rain for", years, "years is:", totalRain);
print("The average rain per year is: ", avgYearRain);
print("The average rain per day is: ", avgDayRain);
答案 0 :(得分:0)
如果我理解正确,您希望变量totalRain包含模拟中所有降雨量的总和。您的代码中存在许多问题,我只会解决其中的一些问题。
问题出在这个if语句中:
if days_of_drought>max_drought:
max_drought=days_of_drought;
else:
days_rained+=1;
if rainfall>=1.5: <--- HERE
days_over15+=1;
if rainfall>=0.5:
totalRain+=1; <-- HERE
avgRain=totalRain/day;
在英语中,这说:&#34;如果降雨量超过1.5英寸,则在所有降雨量的总和上加1。&#34;您可能想说:&#34;将降雨量添加到所有降雨量的总和中。 (不管下雨多少)。&#34;
除此之外,if rainfall>=0.5
没有意义,因为它已经在降雨量超过1.5的分支中,因此肯定高于0.5。
作为旁注,你不需要任何分号。
尝试查看以下内容是否符合您的要求:
totalRain+=rainfall
if days_of_drought>max_drought:
max_drought=days_of_drought
else:
days_rained+=1
if rainfall>=1.5:
days_over15+=1
avgRain=totalRain/day
最后一个计算avgRain
的陈述对我来说似乎有问题。您可能想要确切地考虑该变量的含义以及如何正确计算它。