输入一个年份和月份,打印出该月份有多少天考虑闰年要求使用switch语句编程用c++来写
时间: 2024-10-25 10:03:05 浏览: 34
在C++中,你可以编写一个函数来计算给定年月的天数,并考虑到闰年的条件。这里是一个使用`switch`语句的例子:
```cpp
#include <iostream>
bool is_leap_year(int year) {
if (year % 4 != 0)
return false;
else if (year % 100 != 0)
return true;
else if (year % 400 != 0)
return false;
else
return true;
}
int days_in_month(int month, int year) {
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
if (is_leap_year(year))
return 29;
else
return 28;
default:
std::cout << "Invalid month!";
return -1; // 错误处理
}
}
int main() {
int year, month;
std::cout << "Enter a year and month (1-12): ";
std::cin >> year >> month;
if (month >= 1 && month <= 12) {
int days = days_in_month(month, year);
if (days != -1)
std::cout << "The number of days in the given month (" << month << ") of " << year << " is " << days << "." << std::endl;
else
std::cout << "Days calculation failed!" << std::endl;
} else {
std::cout << "Invalid input for month." << std::endl;
}
return 0;
}
```
在这个程序中,我们首先检查输入的年份是否是闰年,然后根据月份的值用`switch`语句确定每个月的天数。如果输入的月份无效,我们会返回错误信息。
阅读全文