do while循环问题

时间:2014-10-10 17:38:16

标签: c loops

我遇到了一个问题,我写过一个摇滚,纸张,剪刀游戏的do while循环。它永远不会脱离循环。我已经尝试了一切,但似乎没有任何效果。一切看起来都很合理,但也许我错过了一些东西。有人有主意吗?虽然我明白一个简单的解决方法是在每个break语句中添加if,但我想理解为什么循环本身不起作用。

#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");
}

5 个答案:

答案 0 :(得分:4)

这就是测试(谓词)应该用正逻辑写的原因。 De Morgan定律的应用(二元性)转换

rounds != 3 || rounds != 5

!(rounds == 3 && rounds == 5)

明显简化为

true

但不要心疼。 1998年,我修复了这种类型的商业桌面业务应用程序中的缺陷!

答案 1 :(得分:3)

  

我已经尝试了一切,但似乎没有任何效果。

你试过while (rounds != 3 && rounds != 5);吗?

当然不是!尝试它,它会工作。请注意,每个数字不等于3或不等于5,因此条件将始终为true ||

答案 2 :(得分:2)

使用AND而不是OR

像这样:

while (rounds != 3 && rounds != 5);

答案 3 :(得分:2)

rounds != 3 || rounds != 5始终为真 - 任何值rounds都必须不等于3或5。

你想要

rounds != 3 && rounds != 5

答案 4 :(得分:1)

你的停止条件总是如此。

rounds != 3 || rounds != 5  // || = OR

对所有数字的评估结果为true。