如何为我的C++猜谜游戏添加"play again"功能?环路故障

How do I add a "play again" feature to my C++ guessing game? Loop trouble

本文关键字:again play 功能 故障 环路 添加 游戏 我的 C++      更新时间:2023-10-16

所以对于这个任务,我必须包含一个play again函数。也就是说,一旦玩家猜对了,程序就应该让玩家选择是否再玩一遍。此外,我试图包括一个函数,如果用户在5次或更少的猜测中正确猜测,那么程序应该打印"干得好!",如果它需要超过5次猜测,它应该显示"你可以做得更好!"。救救我吧!我是一个编程初学者,我一直在试图解决这个问题。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void )
{
int i, n = 0, r;
int answer;
srand( time( NULL ) );
r = rand() %100 +1;
char userName[15];

printf("Welcome to GUESS MY NUMBER!nnPlease type your name here: ");
scanf("%s", &userName);
printf("nnI am thinking of a number between 1 and 100.nnCan you guess what it is?  ");
while(scanf("%d", &i))
{      
if (n >= 9 && i != r)
{         
printf("nnSorry, the number was %d.n", r);
printf("You should have gotten it by now.n");        
printf("Better luck next time.nn");         
system ("PAUSE");
break;    
}      
if (i > r) 
{         
n++;
printf("Your guess is high. You only get 10 guesses. Try again: ");   
}     
else if (i < r) 
{         
n++;          
printf("Your guess is low. You only get 10 guesses. Try again: ");    
}     
else if (i == r) 
{             
printf("nnCongratulations %s!nYou guessed the number within %d guesses!nWould you  like to play again? y/n?n",userName, n+1,answer);
scanf("%d", &answer);
system ("PAUSE");
break;         
}    
}
return 0;
}

一个简单的方法是创建一个bool变量(最初设置为true),它可以在while语句中检查,并在用户获得继续或不继续的选项后更新。然后把break改成continue,这样就可以了

将整个内容包裹在另一个循环中,并在这个外部循环结束时询问用户是否想要再玩一次。while()或do-while()循环。如果用户说是,则继续循环,否则退出循环。

-Initialize the game
-Load any resources needed (in this case, none)
Begin looping continually
    - Handle input
    - Think
    - Show results
End looping if exited
-Free any resources (in this case, none)
-Exit