问题与循环做
问题描述:
我遇到了一个问题,而我已经写了一个岩石,纸张,剪刀游戏的while循环。它永远不会出现循环。我尝试了一切,但似乎没有任何工作。一切看起来都合乎逻辑,但也许我错过了一些东西。有人有主意吗?虽然我确实知道一个简单的解决方法是为每个if
声明添加break
,但我想了解为什么循环本身不起作用。问题与循环做
#include <stdio.h>
#include <stdlib.h>
int main(){
int rounds,
wins,
max;
do {
printf("Best 2 out of 3 or Best 3 out of 5? (Enter 3 or 5)\n");
scanf_s("%d", &rounds);
printf("%d\n\n", rounds);
if (rounds == 3){
wins = 2;
max = 3;
puts("OK!");
}
else if (rounds == 5){
wins = 3;
max = 5;
puts("\nOK!");
}
else {
printf("Please enter a valid option.\n\n");
}
} while (rounds != 3 || rounds != 5);
system("pause");
}
答
我用尽了一切办法,但似乎没有任何工作。
您试过while (rounds != 3 && rounds != 5);
?
当然不是!尝试一下,它会工作。请注意,每个数字不等于3
或不等于5
,因此条件将始终为true
与||
。
答
使用AND
不是OR
!
像这样:
while (rounds != 3 && rounds != 5);
答
你的停车条件始终为真。
rounds != 3 || rounds != 5 // || = OR
对于所有数字都计算为真。
答
rounds != 3 || rounds != 5
始终是真实的 - 无论价值rounds
有它并不等于3或5
你想
rounds != 3 && rounds != 5
答
这就是为什么测试(谓语)应在正逻辑写入。转换
rounds != 3 || rounds != 5
到
!(rounds == 3 && rounds == 5)
这显然简化了
true
但不心疼德·摩根定律(偶)的应用。 1998年,我修复了这种确切类型的商业桌面业务应用程序的缺陷!
+0
Gotcha。刚才意识到德摩根法律并没有被正确地教给我。打开书的时间。 – Novaea 2014-10-10 17:48:48
你是对的,它的确如此,但是如果满足其中一个条件,'||'也不会返回true吗? – Novaea 2014-10-10 17:43:57
@Novaea;否。请参阅更新。 – haccks 2014-10-10 17:48:26