计算日期之差
#include <stdio.h> int judge_year(int year) { if(year % 400 == 0 || year % 4 == 0 && year % 100 != 0) return 1; else return 0; } int total_days( int year, int month, int day ) { int i, sum = 0; for(i = 1; i < month; i++) { if(i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12) { sum += 31; } else if(i == 4 || i == 6 || i == 9 || i == 11){ sum += 30; } else if(i == 2){ if( judge_year(year) == 1) { sum += 29; } else { sum += 28; } } } sum += day; return sum; } //void swap(char *x, char *y) void swap(int *x, int *y) { int term; term = *x; *x = *y; *y = term; } int main() { int year1, month1, day1, year2, month2, day2; int n, distance, i; scanf("%d", &n); while(n--){ printf("第一个日期:"); scanf("%d %d %d", &year1, &month1, &day1); printf("第二个日期:"); scanf("%d %d %d", &year2, &month2, &day2); if(year1 == year2) { distance = total_days(year1, month1, day1) - total_days(year2, month2, day2); if(distance < 0) { distance *= -1; } } else { distance = 0; if(year1 > year2) { //swap(year1, year2);#1 //swap(month1, month2); //swap(day1, day2); swap(&year1, &year2); swap(&month1, &month2); swap(&day1, &day2); } distance += judge_year(year1) ? 366 - total_days(year1, month1, day1) : 365 - total_days(year1, month1, day1); for(i = year1 + 1; i < year2; i++){ if( judge_year(i) ) { distance += 366; } else { distance += 365; } } distance += total_days(year2, month2, day2); } printf("%d年%d月%d日 到 %d年%d月%d日 有%d天\n", year1, month1, day1, year2, month2, day2, distance); } return 0; }
note:#1忘记取地址了。
一个swap函数省了很多笔墨。