题解 | #计算日期到天数转换#
计算日期到天数转换
https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
#include <stdio.h> //第一种简单数组方法 int main() { int year; int month; int day; scanf("%d %d %d", &year, &month, &day); int sum = day; //闰年数组: int leap_year[12] = { 31,29,31,30,31,30,31,31,30,31,30,31 }; // 1 2 3 4 5 6 7 8 9 10 11 12 //平年数组: int common_year[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; // 1 2 3 4 5 6 7 8 9 10 11 12 //闰年情况: if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { if (month == 1) { sum = day; } else { int j = 0; for (int i = 1; i < month; i++) { sum = sum + leap_year[j++]; } } } //平年情况: else { if (month == 1) { sum = day; } else { int j = 0; for (int i = 1; i < month; i++) { sum = sum + common_year[j++]; } } } printf("%d", sum); return 0; } //第二种暴力方法: int main() { int year; int month; int day; scanf("%d %d %d", &year, &month, &day); int sum = 0; //1 3 5 7 8 10 12 ——31天 //4 6 9 11 ——30天 //闰年2月 ——29天 //平年2月 ——28天 //如果year是闰年 2000 11 15 if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { switch (month) { case 1: sum = day; break; case 2: sum = 31 + day; break; case 3: sum = 31 + 29 + day; break; case 4: sum = 31 + 29 + 31 + day; break; case 5: sum = 31 + 29 + 31 + 30 + day; break; case 6: sum = 31 + 29 + 31 + 30 + 31 + day; break; case 7: sum = 31 + 29 + 31 + 30 + 31 + 30 + day; break; case 8: sum = 31 + 29 + 31 + 30 + 31 + 30 + 31 + day; break; case 9: sum = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + day; break; case 10: sum = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + day; break; case 11: sum = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + day; break; case 12: sum = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + day; break; } } else { switch (month) { case 1: sum = day; break; case 2: sum = 31 + day; break; case 3: sum = 31 + 28 + day; break; case 4: sum = 31 + 28 + 31 + day; break; case 5: sum = 31 + 28 + 31 + 30 + day; break; case 6: sum = 31 + 28 + 31 + 30 + 31 + day; break; case 7: sum = 31 + 28 + 31 + 30 + 31 + 30 + day; break; case 8: sum = 31 + 28 + 31 + 30 + 31 + 30 + 31 + day; break; case 9: sum = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + day; break; case 10: sum = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + day; break; case 11: sum = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + day; break; case 12: sum = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + day; break; } } printf("%d", sum); return 0; }