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

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

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

首先了解一下什么是闰年http://blog.csdn.net/i_peter/article/details/78905439


闰年共有366天(31,29,31,30,31,30,31,31,30,31,30,31)
平年365天(31,28,31,30,31,30,31,31,30,31,30,31)
第一种方法:

    def isLeapYear(self, year):
        '判断是否为闰年'
        year = int(year)
        if year % 4 == 0 and year % 100 != 0:
            return True
        elif year % 400 == 0:
            return True
        return False

    def isTheDayOfTheYear(self):
        year = int(input('输入year:'))
        month = int(input('输入month:'))
        day = int(input('输入day:'))
        dayList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        i = 0
        countDay = 0
        if month > 2 and code.isLeapYear(str(year)):
            countDay += 1
        while i < month - 1:
            i += 1
            countDay += dayList[i - 1]
        countDay += day
        # print('这是%D年的第%D天!' % (year , countDay))
        return countDay
第二种方法:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
    sum = months[month - 1]
else:
    print 'data error'
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
if (leap == 1) and (month > 2):
    sum += 1
print 'it is the %dth day.' % sum
结果:
输入year:2015
输入month:6
输入day:7
这是2015年的第158天!

你可能感兴趣的:(python算法题)