gpt4 book ai didi

c++ - 为什么这个程序打印两次 "nine"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:04:55 24 4
gpt4 key购买 nike

现场版:http://cpp.sh/953y6

代码:

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
// Complete the code.
int num1 = 8, num2 = 11;
for(int n = num1; n <= num2; n++){

if(n <= 9){
switch(n){
case 1: cout << "one\n";
case 2: cout << "two\n";
case 3: cout << "three\n";
case 4: cout << "four\n";
case 5: cout << "five\n";
case 6: cout << "six\n";
case 7: cout << "seven\n";
case 8: cout << "eight\n";
case 9: cout << "nine\n";
}

}
else if(n % 2 == 0){ //even
cout << "even\n";
}
else if(n > 9 && n %2 == 1){ //odd
cout << "odd\n";
}

}

return 0;
}

数字 8 到 11 在 for 循环中循环。 if(n <= 9) 应该只被触发两次,当 n 是 8 和当 n 是 9 时。相反,输出是:

eight
nine
nine
even
odd

为什么?

最佳答案

因为你没有 break 并且它是 fall-through case。

case 8: cout << "eight\n";  // <-- need break here
case 9: cout << "nine\n"; // otherwise it's fall-through to here even input is 8
  • 好的做法是总是switch 的每个 case 之后 break
  • 如果您需要故意失败,请明确说明对失败发表评论。

关于c++ - 为什么这个程序打印两次 "nine"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41627009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com