c++编写一个函数实现月份的输出
时间: 2024-02-05 17:11:14 浏览: 75
下面是一个简单的 C++ 函数,用于输出月份:
```c++
#include <iostream>
#include <string>
using namespace std;
void printMonth(int month) {
string monthName;
switch (month) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = "Invalid month";
break;
}
cout << monthName << endl;
}
int main() {
printMonth(3);
printMonth(13);
printMonth(9);
printMonth(0);
return 0;
}
```
该函数接受一个整数表示月份,使用 switch 语句将其转换为相应的月份名称,并将其打印到控制台。如果传入的值无效,则输出 "Invalid month"。在主函数中,我们调用 printMonth 函数多次,以演示其功能。
阅读全文