如何退出 while 循环(继续)
How to exit a while loop (continue)
我一直在尝试解决一个简单的编码问题(我是 C++ 新手)。
基本上我试图使用
退出 while 循环
continue
或
break
但它不起作用。问题是
cout << "it worked!";
部分未执行。
#include <iostream>
#include <string>
using namespace std;
int main() {
int userChoice=0;
cout<<"1 for addiction and 2 for subtraction\n";
do{
if(cin >> userChoice){
switch (userChoice) {
case 1:
continue;
case 2:
continue;
default:
cout<<"Please select 1 for addiction or 2 for subtraction.\n";
break;
}
}
}while(userChoice!=1 || userChoice!=2);
cout<<"it worked!";
}
int addiction(int a,int b){
return a+b;
}
int subtraction(int a,int b){
return a-b;
}
不可能离开你的循环,因为无论 userChoice
是什么,它总是 "not 1" 或 "not 2"(它永远不会两者都是!)。
因此,由于 continue
将始终进行另一次迭代,并且由于 break
使您跳出 switch
(不是循环),因此您的循环永远不会结束cout
将永远不会被执行。
在我看来,只要 userChoice
不是 1 并且 也不是 2,您就想迭代:
while(userChoice!=1 && userChoice!=2);
这有时会让初学者感到困惑,他们使用像 "userChoice is not 1 or 2" 这样的英语快捷方式,而实际上他们的意思是 "userChoice is neither 1 nor 2" 并且没有意识到 C++ 根本没有 "neither/nor" 结构所以想不通就写错了"userChoice is not 1 or userChoice is not 2"
由于积极因素比消极因素更直观,因此向自己澄清这一点的一种方法是应用德摩根定律;您的固定代码相当于:
while(!(userChoice == 1 || userChoice == 2));
即"loop while it's not the case that userChoice is either 1 or 2"。它可以说是更糟糕的代码,但它可以帮助你的理解以这种方式简要地写出来。
我一直在尝试解决一个简单的编码问题(我是 C++ 新手)。
基本上我试图使用
退出 while 循环continue
或
break
但它不起作用。问题是
cout << "it worked!";
部分未执行。
#include <iostream>
#include <string>
using namespace std;
int main() {
int userChoice=0;
cout<<"1 for addiction and 2 for subtraction\n";
do{
if(cin >> userChoice){
switch (userChoice) {
case 1:
continue;
case 2:
continue;
default:
cout<<"Please select 1 for addiction or 2 for subtraction.\n";
break;
}
}
}while(userChoice!=1 || userChoice!=2);
cout<<"it worked!";
}
int addiction(int a,int b){
return a+b;
}
int subtraction(int a,int b){
return a-b;
}
不可能离开你的循环,因为无论 userChoice
是什么,它总是 "not 1" 或 "not 2"(它永远不会两者都是!)。
因此,由于 continue
将始终进行另一次迭代,并且由于 break
使您跳出 switch
(不是循环),因此您的循环永远不会结束cout
将永远不会被执行。
在我看来,只要 userChoice
不是 1 并且 也不是 2,您就想迭代:
while(userChoice!=1 && userChoice!=2);
这有时会让初学者感到困惑,他们使用像 "userChoice is not 1 or 2" 这样的英语快捷方式,而实际上他们的意思是 "userChoice is neither 1 nor 2" 并且没有意识到 C++ 根本没有 "neither/nor" 结构所以想不通就写错了"userChoice is not 1 or userChoice is not 2"
由于积极因素比消极因素更直观,因此向自己澄清这一点的一种方法是应用德摩根定律;您的固定代码相当于:
while(!(userChoice == 1 || userChoice == 2));
即"loop while it's not the case that userChoice is either 1 or 2"。它可以说是更糟糕的代码,但它可以帮助你的理解以这种方式简要地写出来。