本範例示範如何使用 C 語言結構體儲存年月日,並結合閏年判斷與月份天數累加,計算輸入日期是當年的第幾天(年積日)。此為日期運算的基礎應用,常用於日曆系統、排程演算法等場景。
struct date { int year, month, day; };
int is_leap(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
const int month_day[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
#include <stdio.h>
struct date { int year, month, day; };
int is_leap(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
const int month_day[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int main() {
struct date d;
printf("請輸入日期 (年 月 日):");
scanf("%d %d %d", &d.year, &d.month, &d.day);
int days = d.day;
for (int m = 1; m < d.month; m++) days += month_day[m];
if (is_leap(d.year) && d.month > 2) days++;
printf("%d 年 %d 月 %d 日是當年的第 %d 天\n",
d.year, d.month, d.day, days);
return 0;
}
請輸入日期 (年 月 日):2024 3 1 2024 年 3 月 1 日是當年的第 61 天
此程式結構清晰,展示結構體封裝、函數複用與迴圈累加的基本技巧,適合初學者掌握日期運算核心邏輯。