【问题标题】:How do I add a "play again" feature to my C++ guessing game? Loop trouble如何在我的 C++ 猜谜游戏中添加“再玩一次”功能?循环故障
【发布时间】:2013-03-12 00:47:28
【问题描述】:

所以对于这个作业,我必须包含一个重播功能。这意味着一旦人们猜对了,程序应该让用户选择是否再次播放。另外,我正在尝试包含一个功能,如果用户在 5 次或更少的猜测中正确猜测,那么程序应该打印“Good Job!”如果他们的猜测超过 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!\n\nPlease type your name here: ");
scanf("%s", &userName);
printf("\n\nI am thinking of a number between 1 and 100.\n\nCan you guess what it is?  ");
while(scanf("%d", &i))
{      
if (n >= 9 && i != r)
{         
printf("\n\nSorry, the number was %d.\n", r);
printf("You should have gotten it by now.\n");        
printf("Better luck next time.\n\n");         
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("\n\nCongratulations %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;
}

【问题讨论】:

  • 你的很多代码(包括随机数生成)不在循环中。如果你想让代码重复,它必须是循环的一部分。然后你可以在条件合适时中断。

标签: c++ loops numbers


【解决方案1】:

一个简单的事情是创建一个布尔变量(最初设置为 true),可以在 while 语句中检查并在用户选择继续或不继续后更新。然后只需将休息时间更改为继续,您应该会保持良好状态。

【讨论】:

    【解决方案2】:

    将整个东西包裹在另一个循环中,并在这个外循环结束时,询问用户是否想再玩一次。 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
    

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 1970-01-01
      • 2021-11-02
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多