酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

题目内容: 计算某年某月某日是该年中的第几天。 输入格式: 依次输入年、月和日 输出格式: 输出这一天是该年中的第几天。注意年月日合法性的判定和闰年的计算 输入样例1: 2009 3 2 输出样例1: 这是2009年的第61天 输入样例2: 2009 3 32 输出样例2: 日期有误 时间限制:500ms内存限制:32000kb

以下是使用 Python 语言实现的代码: ```python def day_of_year(year, month, day): # 定义每个月的天数 days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 判断是否为闰年 if (year % 4 == 0 and year % 100!= 0) or year % 400 == 0: days_in_month[2] = 29 # 检查日期合法性 if month < 1 or month > 12 or day < 1 or day > days_in_month[month]: return "日期有误" total_days = 0 for i in range(1, month): total_days += days_in_month[i] total_days += day return f"这是{year}年的第{total_days}天" # 测试 print(day_of_year(2009, 3, 2)) print(day_of_year(2009, 3, 32)) ``` 额外需要注意的逻辑点: 1. 对于闰年的判断要准确,能被 4 整除但不能被 100 整除,或者能被 400 整除的年份为闰年。 2. 处理输入的月份和日期时,要考虑边界情况,确保输入在合理范围内。 3. 计算总天数时,要注意累加的逻辑,确保没有遗漏或重复计算。 [2024-12-17 23:42:32 | AI写代码神器 | 377点数解答]

相关提问