#include <stdio.h>
#define MAXLIMIT 1000
#define MINLIMIT 1
int main()
{int number = 0, valid=0;
do {
printf("Player 1, enter a number between 1 and 1000:\n");
scanf("%d", &number);
valid = number >= MINLIMIT || number <= MAXLIMIT;
if (!valid) {
printf("That number is out of range.\n");
}
} while (!valid);
int guess = 0, chance = 10;
// Allow player 2 to guess and check
do {
printf("Player 2, you have %d guesses remaining\n", chance);
printf("Enter your guess:\n");
scanf("%d", &guess);
if (guess < number){
printf("Too low.\n");
} else if (guess > number) {
printf("Too high.\n");
} else if (guess == number){
printf("Player 2 wins.\n");
}
else if (guess != number && chance == 0)
printf("Player 1 wins.\n");
} while (guess != number && chance > 0);
}
This is currently my code. I'm stucked at the last where once the user has use up their 10 chances, Player 1 wins. Is there anyway for two while loop condition to happen?
CodePudding user response:
SUGGESTION:
Refactor your code:
- Store information about each player (e.g. "name" and "#/guesses") in a struct.
- Create an array of players:
struct player players[2];
- Move your "make a guess" code into a function:
void guess(int number, struct player * player)
. - Whenever you call "guess()", simply check if the #/guesses for that player has been exceeded.
CodePudding user response:
For starters the logical expression
valid = number >= MINLIMIT || number <= MAXLIMIT;
is invalid. You need to use the logical AND operator instead of the logical OR operator
valid = number >= MINLIMIT && number <= MAXLIMIT;
This syntactically incorrect part with do statement
do {
while (guess != number && chance = 0)
printf("Player 1 wins. \n")
}
is redundant.
It is enough to write
if ( guess != number )
{
printf("Player 1 wins. \n");
}
EDIT: After you changed your code in the question then write the if statement within the do-while loop like
if (guess < number){
printf("Too low.\n");
} else if (guess > number) {
printf("Too high.\n");
} else
printf("Player 2 wins.\n");
}
And after the do-while loop write
if ( guess != number )
printf("Player 1 wins.\n");