当前位置:首页 C++ > 正文

C++判断⽉份天数(判断闰年)

作者:野牛程序员:2023-08-11 17:26:07 C++阅读 2754

下面是一个示例程序,展示了如何使用C++来判断一个月份的天数,包括判断是否为闰年:

#include <iostream>

bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int main() {
    int year, month;
    
    std::cout << "请输入年份: ";
    std::cin >> year;

    std::cout << "请输入月份: ";
    std::cin >> month;

    int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    if (month < 1 || month > 12) {
        std::cout << "输入的月份无效" << std::endl;
        return 1;
    }

    if (isLeapYear(year) && month == 2) {
        std::cout << year << "年" << month << "月有 29 天" << std::endl;
    } else {
        std::cout << year << "年" << month << "月有 " << daysInMonth[month - 1] << " 天" << std::endl;
    }

    return 0;
}

在这个示例中,使用了 isLeapYear 函数来判断是否为闰年。然后,从用户输入获取年、月,并根据输入的年月判断该月有多少天。如果是闰年且是二月,则有29天,否则根据数组 daysInMonth 来获取对应月份的天数。

请注意,这个示例仅适用于公历,对于其他历法(例如农历)可能需要更复杂的算法。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击