可以使用以下步驟來求任意兩個日期之間的天數:
下面是一個示例代碼:
#include <stdio.h>
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1;
} else {
return 0;
}
}
int getDaysOfMonth(int year, int month) {
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year)) {
return 29;
} else {
return days[month - 1];
}
}
int getTotalDays(int year, int month, int day) {
int totalDays = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
for (int i = 1; i < month; i++) {
totalDays += getDaysOfMonth(year, i);
}
totalDays += day;
return totalDays;
}
int main() {
int year1, month1, day1;
int year2, month2, day2;
printf("請輸入第一個日期(年 月 日):");
scanf("%d %d %d", &year1, &month1, &day1);
printf("請輸入第二個日期(年 月 日):");
scanf("%d %d %d", &year2, &month2, &day2);
int totalDays1 = getTotalDays(year1, month1, day1);
int totalDays2 = getTotalDays(year2, month2, day2);
int days = totalDays2 - totalDays1;
printf("兩個日期之間的天數為:%d\n", days);
return 0;
}
希望對你有幫助!