如果按某个按钮,如何重新启动程序

时间:2014-09-29 16:50:14

标签: c

我最近写了这个"猜数字"程序。我的问题是,当我按下" y"我希望程序重新启动。在"再次播放"问题来了。有任何想法吗? :)

srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;


 printf("I'm thinking of a number between 1 and 100\n");
 printf("What is your guess?\n");

while(1)

{

 counter++; 

 scanf("%d", &guess);

 if (guess == secretNumber) 
 {
     printf("It took you %d tries\n", counter); 
     printf("Play again (y/n)?\n");
     break;

 }

 if (guess < secretNumber) 
  {   
     printf("Too low!\n"); 
  }


 if (guess > secretNumber) 

 { 
     printf("Too high!\n");
 }

4 个答案:

答案 0 :(得分:2)

将您拥有的整个代码段放在另一个while(1)语句中:

srand(time(NULL));
while(1)
{
    int secretNumber = rand()%100 + 1;
    int guess = 0;
    int counter = 0;
    printf("I'm thinking of a number between 1 and 100\n");
    printf("What is your guess?\n");

    while(1)
    {
        //code for guessing number
    }

    printf("Play again? ");
    if (getchar() != 'y')
    {
        break;
    }
}

答案 1 :(得分:0)

printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");

需要在你的循环中,除非你只想给他们一个猜测。

做你想做的最简单的方法就是在他们猜对的时候创建一个新的密码,如果他们回答“否”到“你想再玩一次吗?”,就可以摆脱你的循环。

答案 2 :(得分:0)

您可以使用其他变量。如下。

char userinput = 'y';
while(input == 'y')
{
    //your logic here
    //And at the end use one scanf

    printf("Play again (y/n)?\n");
    scanf("%c", &userinput);
} 

您需要添加一个新变量,在上面的例子中,它是userinput。

答案 3 :(得分:0)

使用while循环,使用bool类型的循环变量,最后说dec为True。放置代码并初始化循环中的所有变量,以便它们可以具有本地范围并在每次循环完成时被销毁。如果用户按下&#34; y&#34;请求用户输入dec变量。将其设置为True,否则将其设置为False。所以这次可以跳过循环

代码可能如下:

char cha;
bool dec=True;
while(dec){
srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");

while(1)
{
    //code for guessing number
}

printf("Play again? ");
scanf("%c",&cha);
if (char== 'y')
    bool=True;
else bool=False;
}