【程序 4】
题目:输入某年某月某日,判断这一天是这一年的第几天?
1.程序分析:以 3 月 5 日为例,应该先把前两个月的加起来,然后再加上 5 天即本年的第几
天,特殊
情况,闰年且输入月份大于 3 时需考虑多加一天。
2.程序源代码:
def is_leap_year(year): return (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)) def day_of_year(year, month, day): months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334) if not (1 <= month <= 12): print('data error: month should be between 1 and 12') return if not (1 <= day <= 31): print('data error: day should be between 1 and 31') return sum_days = months[month - 1] + day if is_leap_year(year) and month > 2: sum_days += 1 return sum_days # 获取用户输入 year = int(input('year:\n')) month = int(input('month:\n')) day = int(input('day:\n')) # 计算并输出结果 result = day_of_year(year, month, day) if result is not None: print('it is the %dth day.' % result)
方法二:
def is_leap_year(year): """判断是否是闰年""" if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): return True return False def days_in_month(year, month): """返回给定年月的天数""" if month == 2: if is_leap_year(year): return 29 else: return 28 elif month in [4, 6, 9, 11]: return 30 else: return 31 def day_of_year(year, month, day): """返回给定日期是这一年的第几天""" total_days = 0 for m in range(1, month): total_days += days_in_month(year, m) total_days += day return total_days # 示例用法 year = 2024 month = 9 day = 10 print(f"{year}年{month}月{day}日是这一年的第{day_of_year(year, month, day)}天")
标签:return,第几天,某日,days,month,year,某年某月,day From: https://www.cnblogs.com/liu-zhijun/p/18407314