题解 | #计算日期到天数转换#
计算日期到天数转换
http://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
主要是考察判断闰年的问题。 1、能被400整除的年份是闰年; 2、能被4整除但不能被100整除的年份是闰年。 其他情况都是非闰年。
#include<stdio.h>
//判断是否闰年:四年一润,百年不润,四百年再润。
int isLeap(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return 1;
else return 0;
}
int main() {
int year, month, day, count = 0;
int leapyear[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30}; //闰年
int disleapyear[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30}; //非闰年
while (~scanf("%d %d %d", &year, &month, &day)) {
int leap = isLeap(year);
for (int i = 1; i < month; i++) {
if (leap) count += leapyear[i];
else count += disleapyear[i];
}
printf("%d\n", count + day);
}
}