简体   繁体   中英

C Program not exiting?

I have an assignment where I have to write a program for paper-scissor-rock.

You play against "PC", and the first to score 2 points win. After scoring 2 points, the program should stop and print out the winner.

Here is my code:

int main()
{
srand(time(NULL));
int dinP = 0;
int pcP = 0;

printf("Welcome to rock paper scissor!\n");

while(dinP != 2 || pcP != 2){

int player, computer, letsgo;

printf("Press any key to continue.\n");
scanf("%d", &letsgo);

printf("Your turn!\n 0 for Paper\n 1 for Rock\n 2 for Scissor\n");
scanf("%d", &player);

computer = rand() % 3;
printf("computers picked",computer);

if (player == 0 && computer == 0 || player == 1 && computer == 1 || player == 2 && computer == 2)

{

//    printf("Player picked %d\n", player);
//    printf("Computer picked %d\n", computer);
    printf("Therefore the result is 0 you ended up equal!\n");

}

if (player == 0 && computer == 1 || player == 1 &&computer == 2 || player == 2 && computer == 0)

{

 //   printf("player picked %d\n", player);
 //   printf("Computer picked %d\n", computer);
    printf("Player wins!\n 1 point for Player\n");
    dinP++;

}


if(player == 0 && computer == 2 || player == 1 && computer == 0 || player == 2 && computer == 1)

{

  //  printf("player picked %d\n", player);
 //   printf("Computer picked %d\n", computer);
    printf("Computer wins!\n Computer Wins! 1 point for the Computer\n");
    pcP++;

}

if(player < 0 || player >= 3)

{
    printf("Please enter a valid number\n In other words, pick either rock, paper or scissor.\n");
}

printf("dinP  : %d - - - - - pcP : %d", dinP, pcP);

}

if(dinP == 2){
    printf("You won\n");
  //  printf("p: %d", dinP);
}else if(pcP == 2){
    printf("Pc Won\n");
  //  printf("p: %d", pcP);
}

return 0;

}

After scoring 2 points, the program doesnt stop and keeps asking for my input. Any suggestions why it doesnt end after 2 points?

Think about this part:

while(dinP != 2 || pcP != 2)

The expression will be false when they're BOTH equal to 2. It's going to keep running until the player and the computer both have 2 points. To fix this, just change the || to && .

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