龙空技术网

输入某年某月某日,判断这一天是这一年的第几天

GIS开发 154

前言:

今天小伙伴们对“python输出某年某月的日历”大致比较关注,朋友们都需要剖析一些“python输出某年某月的日历”的相关内容。那么小编也在网摘上收集了一些有关“python输出某年某月的日历””的相关知识,希望小伙伴们能喜欢,兄弟们一起来了解一下吧!

今天的Python题目是:输入某年某月某日,判断这一天是这一年的第几天?这个题目很有意思,假如输入【2019年1月1日】,会反馈给我该天是2019年的第一天。

我们来分析一下:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。

先输入年月日:

year = int(input('year:\n'))month = int(input('month:\n'))day = int(input('day:\n'))

定义一个months列表,用于表示该月之前月的日数:

months = [0,31,59,90,120,151,181,212,243,273,304,334]

我们判断输入的月份是否正确输入,如果正确输入,我们先求出在该月之前的日数,如果输入错误,则打印警告信息:

if 0 <= month <= 12: s= months[month - 1]else: print('data error')

我们将计算得到的日数和输入的日数相加得到天数的初值:

s= s+ day

接下来我们需要判断是否是润年,如果是闰年且输入月份大于3时需考虑多加一天:

leap = 0if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): leap = 1if (leap == 1) and (month > 2): s+= 1

完整代码如下:

year = int(input('year:\n'))month = int(input('month:\n'))day = int(input('day:\n'))s = 0months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]if 0 <= month <= 12: s = months[month - 1]else: print('data error')s += dayleap = 0if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): leap = 1if (leap == 1) and (month > 2): s += 1print('it is the %dth day.' % s)

标签: #python输出某年某月的日历 #python输入年月日输出天数 #c语言求某年某月某日是该年的第几天