【程序 4】
题目:输入某年某月某日,判断这一天是这一年的第几天?
1.程序分析:以 3 月 5 日为例,应该先把前两个月的加起来,然后再加上 5 天即本年的第几
天,特殊
情况,闰年且输入月份大于 3 时需考虑多加一天。
2.程序源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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) |
方法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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)}天" ) |
柳志军:13418977808(手机微信),QQ:93684042
分类:
Python练习题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律