class STDYLTSW:
def __init__(self, year, month, day):
# 记录当前日期 的三个属性
self.day = day
self.month = month
self.year = year
self.date = (1990, 1, 1) # 初始日期
self.days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30] # 跟上月的天数之差
self.totalDays = 0
def judge_year(self):
# 判断闰年 是 返回1 否返回0
if (self.year % 4 == 0 and self.year % 100 != 0) or (self.year % 400 == 0):
return 1
else:
return 0
def cal_total_days(self):
# 计算年和年之间的天数之差
t = self.date[0] # 将1990赋给t
while t < self.year:
if self.judge_year() == 1:
self.totalDays += 366
else:
self.totalDays += 365
t = t + 1
# 计算月和月之间的天数之差
i = 0
if self.judge_year() == 1:
self.days[2] += 1
while i < self.month:
self.totalDays += self.days[i]
i += 1
# 计算最后天数之差
self.totalDays += self.day
def show_info(self):
print("{}/{}/{}与1990/1/1天数之差是{}天".format(self.year, self.month, self.day, self.totalDays))
result = self.totalDays % 5
# 判断是打鱼还是晒网
if 0 < result < 4:
print("今天打鱼")
else:
print("今天晒网!")
y, m, d = [int(i) for i in input().split()]
p = STDYLTSW(y, m, d)
p.cal_total_days()
p.show_info()
三天打鱼两天晒程序,用面向对象的方式编写,结果老是多了几天?不知道为什么?
以上是面向对象的代码?
面向过程的正确代码如下:
# 判断是否是闰年 是的返回1 否返回0
def run_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return 1
else:
return 0
def count_day(currentDay):
perMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]
totalDay = 0
year = 1990
while year < currentDay['year']:
# 求出指定日期之前的每一年的天数之和
if run_year(year) == 1:
totalDay += 366
else:
totalDay += 365
year += 1
if run_year(currentDay['year']) == 1:
perMonth[2] += 1
# 如果是闰年,二月份是29天
i = 0
while i < currentDay['month']:
# 将本年的天数累加到totalDay中
totalDay += perMonth[i]
i += 1
totalDay += currentDay['day']
return totalDay
if __name__ == '__main__':
# while True:
print("输入指定日期包括年、月、日。如:1999 1 31")
year, month, day = [int(i) for i in input().split()]
# 定义一个日期字典
today = {'year': year, 'month': month, 'day': day}
totalDay = count_day(today)
# 求出指定日期距离1990年1月1日的天数
print("{}年{}月{}日与1990年1月1日相差{}天".format(year, month, day, totalDay))
# 天数%5 判断输出打鱼还是晒网
result = totalDay % 5
if 0 < result < 4:
print("今天打鱼!")
else:
print("今天晒网!")
麻烦老师解答一下。