用户输入月份 打印出该月份对应的天数 二月份需要计算平年还是闰年 规则是4润 100不润 400润 c++switch
时间: 2025-06-14 09:17:17 浏览: 12
在C++中,你可以通过`switch`语句实现这个功能。首先,你需要获取用户输入的月份,然后根据月份检查它有多少天。对于二月,需要判断是否为闰年。以下是大致的代码示例:
```cpp
#include <iostream>
bool is_leap_year(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
}
else {
return true;
}
}
else {
return false;
}
}
int get_days_in_month(int month) {
switch (month) {
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
return 31;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
return 30;
case 2: // February
return is_leap_year(year) ? 29 : 28; // 使用当前年份判断闰年
default: // 非法月份
std::cout << "Invalid month!";
return -1;
}
}
int main() {
int month;
std::cout << "Enter the month: ";
std::cin >> month;
if (get_days_in_month(month) != -1) {
std::cout << "The number of days in " << month << " is: " << get_days_in_month(month);
}
return 0;
}
```
在这个程序里,我们首先定义了一个辅助函数`is_leap_year`来检查是否为闰年,然后在`get_days_in_month`函数中使用`switch`根据月份返回相应的天数,特别地处理了二月份的特殊情况。在`main`函数中,接收用户的输入并调用上述方法。
阅读全文
相关推荐


















