C语言每日一练
2021年9月24日
输入某年某月某日,判断这一天是这一年的第几天?
这题唯一难点就是判断闰年。
闰年(Leap Year)是为了弥补因人为历法规定造成的年度天数与地球实际公转周期的时间差而设立的。补上时间差的年份为闰年。闰年共有366天(1月~12月分别为31天、29天、31天、30天、31天、30天、31天、31天、30天、31天、30天、31天)。
可以用一句简单的话判断是否为闰年:四年一闰,百年不闰,四百年再闰。
#include <stdio.h> int if_leap_year(int year); /* 平年和闰年的月份日数 */ int comm_mon[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int leap_mon[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int main() { int year = 0; int mon = 0; int day = 0; int count = 0; //当年第几天 int i = 0; printf("请输入一个年月日\n"); scanf("%d%d%d", &year, &mon, &day); for(i = 0; i < mon - 1; i++) if(if_leap_year(year)) //如果为闰年 count += leap_mon[i]; else count += comm_mon[i]; count += day; printf("这是%d年的第%d天\n", year, count); return 0; } /** * @brief 是否为闰年 * @param year:年份 * @return 0:不是,1:是 */ int if_leap_year(int year) { if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) return 1; else return 0; }