【程序 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)}天")

  

    

posted on   柳志军  阅读(195)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律



点击右上角即可分享
微信分享提示