要计算某个月份的天数,需要考虑年份是否为闰年,因为闰年的2月份有29天,而非闰年的2月份只有28天。以下是一个C++程序,用于输入年份和月份,并输出该月的天数:

include <iostream>
using namespace std;

// 判断是否为闰年
bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// 获取某个月的天数
int getDaysInMonth(int year, int month) {
    switch (month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            return 31;
        case 4: case 6: case 9: case 11:
            return 30;
        case 2:
            return isLeapYear(year) ? 29 : 28;
        default:
            return -1; // 无效的月份
    }
}

int main() {
    int year, month;

    // 输入年份和月份
    cout << "请输入年份: ";
    cin >> year;
    cout << "请输入月份: ";
    cin >> month;

    // 获取并输出该月的天数
    int days = getDaysInMonth(year, month);
    if (days == -1) {
        cout << "无效的月份!" << endl;
    } else {
        cout << year << "年" << month << "月共有" << days << "天。" << endl;
    }

    return 0;
}

代码说明:

  1. isLeapYear函数:用于判断某年是否为闰年。闰年的规则是:

    • 能被4整除但不能被100整除,或者能被400整除的年份是闰年。
  2. getDaysInMonth函数:根据月份返回该月的天数。2月份的天数取决于是否为闰年,其他月份的天数是固定的。

  3. main函数:程序的主函数,负责输入年份和月份,并调用getDaysInMonth函数来获取该月的天数,最后输出结果。

示例运行:

请输入年份: 2023
请输入月份: 2
2023年2月共有28天。
请输入年份: 2024
请输入月份: 2
2024年2月共有29天。

这个程序可以正确处理闰年和非闰年的情况,并输出正确的月份天数。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐