I had to isolate part of my program for a program that plays a game and keeps track of your losses and wins for the duration of your game. However, my losses variable only increments to at most 1, but if my wins variable increments then it resets the losses back to 0. Also once I exit the while loop it resets losses to 0 again. Wins functions normally.
We have tried swapping where wins and losses gets incremented in the if/else clauses. We have also changed all bools to just 0 and 1's and of course I've isolated the problematic code away from the rest of the program. I have print statements everywhere to keep track of variable values. An I just have the if usrWins switching between true and false for the entirety of continueGame until continueGame is false for testing.
#include <stdio.h>
int main() {
int wins = 0; //wins is 0
int losses = 0; //loses is 0
char usrGame; //user yes or no answer
int continueGame = 1; //replay game
int usrWin = 1; //if the user wins a round
while (continueGame){ //until user quits
if (!usrWin){ //increment wins
losses++;
printf("You Losses!\n");
printf("Wins: %d\n",wins);
printf("Losses: %d\n",losses);
}
else{ //increment losses
wins++;
printf("You Win!\n");
printf("Wins: %d\n",wins);
printf("Losses: %d\n",losses);
}
printf("Bool: %d Wins: %d Losses: %d\n",usrWin,wins,losses);
printf("\nPlay again? ");
scanf("%s",&usrGame); //prompt if user wants to continue, adding to wins and losses
printf("\n");
if (usrGame != 'y'){ //if not, end loop
continueGame = 0;
}
else{
if (usrWin){ //change usrWin bool
usrWin = 0;
}
else{
usrWin = 1;
}
}
}
printf("Wins: %d Losses: %d\n",wins,losses); //display results
return 0;
}
Expected wins to increment, then loses, then wins etc. and finally prints out final value when user ends game. Wins works but losses never goes past 1, rests to 0 if wins increments or the game is ended.
Output looks like:
You Win!
Wins: 1
Losses: 0
Bool: 1 Wins: 1 Losses: 0
Play again? y
You Losses!
Wins: 1
Losses: 1
Bool: 0 Wins: 1 Losses: 1
Play again? y
You Win!
Wins: 2
Losses: 0
Bool: 1 Wins: 2 Losses: 0
Play again? y
You Losses!
Wins: 2
Losses: 1
Bool: 0 Wins: 2 Losses: 1
Play again? n
Wins: 2 Losses: 0
///////////And for a case where I always have usrWin = 0///////////
You Losses!
Wins: 0
Losses: 1
Bool: 0 Wins: 0 Losses: 1
Play again? y
You Losses!
Wins: 0
Losses: 1
Bool: 0 Wins: 0 Losses: 1
Play again? n
Wins: 0 Losses: 0