题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <stdio.h> #include<stdbool.h> //每月天数 int table[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; bool IsRunYear(int year) { return ((year % 4 == 0)&&(year%100!=0))||(year%400==0); } int NumberYear(int year) { if (IsRunYear(year) == 0) return 365; else return 366; } int main() { int year, month, day, newyear, newmonth, newday, number; while ((scanf("%04d%02d%02d\n%04d%02d%02d", &year, &month, &day, &newyear, &newmonth, &newday)) != EOF) { if (year == newyear && month == newmonth ) { number = newday - day + 1; } if (year == newyear && month != newmonth) { int row = IsRunYear(year); number = table[row][month] - day - 1; while (month + 1 != newmonth) { number += table[row][++month]; } number += newday; } else { number = 0; int row = IsRunYear(year); for (int i = 0; i < month; i++) { number += table[row][i]; } number += day; int sum = NumberYear(year) - number + 1; while (year + 1 != newyear) { sum += NumberYear(++year); } int newrow = IsRunYear(newyear); for (int j = 0; j < newmonth; j++) { sum += table[newrow][j]; } sum += newday; number = sum; } printf("%d", number); } return 0; }