不同的 while 循环是或否条件

different while loop yes or no conditions

本文关键字:条件 循环 while      更新时间:2023-10-16

这很令人沮丧,看我希望循环仅在用户输入"N"或"n"时中断。

#include <iostream>
int main()
{
char abc;
std::cin >> abc;
while (abc != 'N' || abc != 'n')
{
std::cout << "hello worldn";
std::cin >> abc;
}
system("pause");   
return 0;
}

这些工作:

while(abc == 'Y' || abc == 'y')
while(abc == 'N')

但是为什么?

更改

while (abc != 'N' || abc != 'n')

while (abc != 'N' && abc != 'n')

因为(abc != 'N' || abc != 'n')总是正确的。

只需将"||"更改为"&&"即可。

while (abc != 'N' && abc != 'n').

德摩根定律的应用将在这里为您提供帮助:

!(abc == 'N' || abc == 'n')(abc != 'N' && abc != 'n')相同。

你编写它的方式将导致程序循环:(abc != 'N' || abc != 'n')等同于!(abc == 'N' && abc == 'n')当然是!(false)

表达式的否定

(abc == 'Y' || abc == 'y')

可以写成

!(abc == 'Y' || abc == 'y')

并重写为

( !( abc == 'Y' ) && !(abc == 'y' ) )

最后作为

( ( abc != 'Y' ) && (abc != 'y' ) )

或者干脆

( abc != 'Y' && abc != 'y' )

所以循环的控制语句应该看起来像

while (abc != 'N' && abc != 'n')

此外,从逻辑上讲,最好将其替换为do-while循环。例如

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char abc;
do
{
std::cout << "hello worldn";
std::cin >> abc;
} while ( abc != 'N' && abc != 'n' );
system("pause");   
return 0;
}