学习日记1:一个小问题用C与python的不同实现
**问题描述:**输入某年某月某日,判断这一天是这一年的第几天?
1.程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊
情况,闰年且输入月份大于2时需考虑多加一天。
C实现代码:
#include<stdio.h>
main()
{
int year,month,day,leap;
scanf("%d.%d.%d",&year,&month,&day);
switch(month) //case 前标号从大到小,使天数一直向下累加
{
case 12:day=day+30;
case 11:day=day+31;
case 10:day=day+30;
case 9:day=day+31;
case 8:day=day+31;
case 7:day=day+30;
case 6:day=day+31;
case 5:day=day+30;
case 4:day=day+31;
case 3:day=day+28;
case 2:day=day+31;
}
if(year%400==0||(year%4==0&&year%100!=0)) /*判断是不是闰年*/
leap=1;
else
leap=0;
if(leap==1&&month>2) /*如果是闰年且月份大于2,总天数应该加一天*/
day++;
printf("It is the %dth day.",day);
}
python实现代码:
# 判断某年某月某日是第几天
import datetime
def is_leap_year(year):
"""
判断year是否是闰年
是则返回Ture
不是返回False
"""
is_leap = False
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
is_leap = True
return is_leap
def main():
input_date_str = input('请输入日期(yyyy/mm/dd):')
input_date = datetime.datetime.strptime(input_date_str, '%Y/%m/%d') # 解析用户输入的日期
print(input_date) # 以datetime格式输出输入的日期
year = input_date.year
month = input_date.month
day = input_date.day
days_in_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # 使用元组存储每月的天数
days = sum(days_in_month[:month-1]) + day # 取出用户输入月份包括之前的月份对应的天数并求和
if month > 2 and is_leap_year(year):
days += 1
'''
用list实现该处功能:
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(year):
days_in_month[1] = 29
days = sum(days_in_month[:month-1]) + day
'''
print('{}年{}月{}日是本年第{}天'.format(year, month, day, days))
if __name__ == '__main__':
main()
该问题较为简单,C语言实现时套用switch()选择语句按照题目要求顺着写即可(case正序也可,除了必要变动,还需在每个case语句结尾加break语句);
python实现时重点是datetime模块函数的调用,以及将每月天数存放在元组(或列表中,实际上用集合、字典等数据结构也可完成)。
(ps:python中实际上自带一个方法可将日期化为天数,但本文为了学习四种数据结构故作,有兴趣的童鞋可以自己查阅相关资料)
刚刚开始学习编程,不免会有些错误或表达问题,希望大佬们帮忙指出,共同进步