int month_ping(int n) { switch(n) { case 1:return 31; case 2:return 28; case 3:return 31; case 4:return 30; case 5:return 31; case 6:return 30; case 7:return 31; case 8:return 31; case 9:return 30; case 10:return 31; case 11:return 30; case 12:return 31; } }哪出错了
时间: 2024-02-25 16:57:16 浏览: 50
这段代码存在两个问题:
1. 函数缺少返回值。当输入的参数不为 1~12 时,没有返回值,会导致函数出现未定义行为。
2. 当输入的参数为 11 时,应该返回 30,但是代码中返回的是 31,这是一个错误。
修改后的代码如下:
```c++
int month_ping(int n) {
switch(n) {
case 1: return 31;
case 2: return 28;
case 3: return 31;
case 4: return 30;
case 5: return 31;
case 6: return 30;
case 7: return 31;
case 8: return 31;
case 9: return 30;
case 10: return 31;
case 11: return 30;
case 12: return 31;
default: return -1; // 返回一个错误值,表示输入的参数不合法
}
}
```
同时,为了更好地排除问题,建议在函数中添加一些调试信息,例如:
```c++
int month_ping(int n) {
switch(n) {
case 1: cout << "January" << endl; return 31;
case 2: cout << "February" << endl; return 28;
case 3: cout << "March" << endl; return 31;
case 4: cout << "April" << endl; return 30;
case 5: cout << "May" << endl; return 31;
case 6: cout << "June" << endl; return 30;
case 7: cout << "July" << endl; return 31;
case 8: cout << "August" << endl; return 31;
case 9: cout << "September" << endl; return 30;
case 10: cout << "October" << endl; return 31;
case 11: cout << "November" << endl; return 30;
case 12: cout << "December" << endl; return 31;
default: cout << "Invalid input!" << endl; return -1;
}
}
```
这样,在调用函数时就能够看到输出的月份信息,方便我们进行调试。
阅读全文