C 程序不退出?

标签 c loops

我有一项作业,我必须为剪刀石头布编写程序。

您与“PC”对战,第一个获得 2 分的玩家获胜。获得 2 分后,程序应停止并打印出获胜者。

这是我的代码:

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;

获得 2 分后,程序不会停止并继续询问我的输入。有什么建议为什么它在 2 点后没有结束吗?

最佳答案

想想这部分:

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

当它们都等于 2 时,表达式将为 false。它将继续运行,直到玩家和计算机都得到 2 分。要解决此问题,只需将 || 更改为 &&

关于C 程序不退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36901643/

相关文章:

c - 使用 i++(或++i)真的是一个好习惯吗?

c - 快速舍入数字 >= 0 到 2 的特定幂的倍数

javascript - 使用 'for' 循环合并两个排序数组...如何在循环结束时阻止 'i' 增加

c++ - 意外的无限循环 (C++)

javascript - 在循环中 react onClick 事件

c++ - 使用 getline 从文本文件创建 2 个并行字符串数组

c - 在哪里使用这个 while 循环?

clion.我无法理解 Clion 中发生的 scanf 错误

c - 如何确定linux控制消息中多个辅助消息的大小

java - 为什么这个一直循环?