温馨提示×

c语言怎么计算某年某月的天数

小亿
122
2023-11-15 19:34:52
栏目: 编程语言

在C语言中,可以通过编写函数来计算某年某月的天数。以下是一个示例程序:

#include <stdio.h>

int isLeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return 1; // 是闰年
    } else {
        return 0; // 不是闰年
    }
}

int getDaysInMonth(int year, int month) {
    int days;

    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            days = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;
        case 2:
            if (isLeapYear(year)) {
                days = 29;
            } else {
                days = 28;
            }
            break;
        default:
            days = -1; // 无效的月份
            break;
    }

    return days;
}

int main() {
    int year, month;

    printf("请输入年份和月份(用空格隔开):");
    scanf("%d %d", &year, &month);

    int days = getDaysInMonth(year, month);

    if (days == -1) {
        printf("无效的月份!\n");
    } else {
        printf("%d年%d月的天数为:%d\n", year, month, days);
    }

    return 0;
}

在上述程序中,isLeapYear() 函数用于判断某年是否是闰年,getDaysInMonth() 函数根据传入的年份和月份计算天数。程序首先从用户输入中获取年份和月份,然后调用 getDaysInMonth() 函数计算天数并打印结果。

0