不同的 while 循环是或否条件
different while loop yes or no conditions
这很令人沮丧,看我希望循环仅在用户输入"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;
}
相关文章:
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 在循环条件 i<sqrtN(预先计算)和 i*i<N 中,C++哪个更有效?
- 尽管条件为真,循环仍停止
- 为什么我不能在 for 循环中出现这样的条件?(C++)
- C++ 即使不满足条件,循环也会终止
- 具有迭代器和自定义步长的循环结束条件
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- 为什么我不能将 size() 函数编写为 while 循环中的条件?
- 虽然循环即使应用了错误条件也不会退出
- 当循环在条件C++之前停止工作时
- Leetcode C++用于循环条件
- 当满足条件时,While循环未结束
- 对于检查 >=0 终止条件时的循环索引类型
- 调用以条件循环(c++)
- 使用布尔条件c++循环时无法退出
- 在条件C++循环语句中向SQLite3表中插入条目