简体   繁体   中英

Issue with do while loop

I've run into an issue with a do while loop for a rock, paper, scissors game I've written. It never breaks out of the loop. I've tried everything, but nothing seems to work. Everything looks logically sound, but maybe I'm missing something. Anyone have any ideas? While I do understand that a simple fix would be to add a break to each if statement, I want to understand why the loop itself does not work.

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

This is why tests (predicates) should be written in positive logic. Application of De Morgan's law (duality) converts

rounds != 3 || rounds != 5

into

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

which clearly simplifies to

true

But don't feel bad. In 1998 I fixed a defect in a commercial desktop business application of this exact type!

I've tried everything, but nothing seems to work.

Did you tried while (rounds != 3 && rounds != 5); ?

Of course not! Try it and it will work. Note that every number is either not equal to 3 or not equal to 5 and hence the condition will always be true with || .

Use AND not OR !

Like this:

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

rounds != 3 || rounds != 5 rounds != 3 || rounds != 5 is always true - whatever value rounds has it has to be unequal to either 3 or 5.

You want

rounds != 3 && rounds != 5

Your stopping condition is always true.

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

evaluates to true for all numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM