輸入年、月、日 (如 2012 4 24),輸出該日期是當年的第幾天。核心在於正確判斷閏年並累加前幾個月天數。
格里曆閏年規則:
程式碼實作:(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
void theDayOfYear() {
int nonleapYear[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int leapYear[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
int year, month, day, num = 0;
printf("please input date like: 2012 4 24\n");
scanf("%d %d %d", &year, &month, &day);
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
for (int i = 0; i < month - 1; i++) num += leapYear[i];
} else {
for (int i = 0; i < month - 1; i++) num += nonleapYear[i];
}
num += day;
printf("the day of year is: %d\n", num);
}
please input date like: 2012 4 24
the day of year is: 115
int cumDays[12] = {0,31,59,90,...}; 查表 O(1)此問題是「日期運算」基礎。進階可嘗試:計算兩日期間隔天數、求 N 天后日期、判斷星期幾 (蔡勒公式)、實作萬年曆程式。日期處理看似簡單,實則包含曆法、時區、閏秒等複雜細節,是軟體工程中常見的坑點。