首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C 語言結構體求指定日期為當年第幾天

     編輯:關於C

結構體封裝日期與年積日計算

本範例示範如何使用 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};

計算邏輯

  1. 讀取年、月、日存入結構體變數。
  2. 若為閏年且月份超過 2 月,基準天數加 1。
  3. 迴圈累加輸入月份之前所有月份的天數。
  4. 加上當月日數,即得年積日。

完整可執行程式碼

#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 天

此程式結構清晰,展示結構體封裝、函數複用與迴圈累加的基本技巧,適合初學者掌握日期運算核心邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved