gpt4 book ai didi

c - 两个问题,为什么双重打印以及如何重新开始! C编程

转载 作者:太空宇宙 更新时间:2023-11-04 05:55:46 24 4
gpt4 key购买 nike

我正在用 C 编写最简单的游戏 - 猜数字游戏。游戏本身运行良好。耶我。问题是我不知道如何重新开始。见下面的代码:

  int main()
{
int number, innum, times = 0;
char playAgain;
srand((unsigned)time(NULL));
number = 5;//rand() % 1000;
for(;;)
{
while(innum != number)
{

printf("Enter a number: ");
scanf("%d", &innum);

if(innum > number)
printf("The entered number is too big!\n");
if(innum < number)
printf("The entered number is too small!\n");

times++;

if(innum == number)
{
printf("Congrats you guessed right!\n");
printf("It took you %d tries\n", times);
}

}

printf("Do you want to play again?");
scanf("%c", &playAgain);
if(playAgain == 'n')
break;


}
return 0;
}

第一个问题是它打印“Do you want to play again?”两次。这是为什么?另一个问题是,如何让游戏重新开始?

提前致谢。

最佳答案

这应该适合你:

(我做了什么?通过scanf添加了一个空格,并将numbertimesinnum的声明放在for循环中)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

int number, innum, times;
char playAgain;
srand((unsigned)time(NULL));

for(;;) {

/*Declare the variables here*/
number = 5; //rand() % 1000;
innum = 0;
times = 0;

while(innum != number) {

printf("Enter a number: ");
scanf("%d", &innum);

if(innum > number)
printf("The entered number is too big!\n");
if(innum < number)
printf("The entered number is too small!\n");

times++;

if(innum == number) {
printf("Congrats you guessed right!\n");
printf("It took you %d tries\n", times);
}

}

printf("Do you want to play again?");
scanf(" %c", &playAgain);
//^Added space here to 'eat' any new line in the buffer
if(playAgain == 'n')
break;


}

return 0;

}

可能的输出:

Enter a number: 2
The entered number is too small!
Enter a number: 6
The entered number is too big!
Enter a number: 5
Congrats you guessed right!
It took you 3 tries
Do you want to play again?y
Enter a number: 3
The entered number is too small!
Enter a number: 5
Congrats you guessed right!
It took you 2 tries
Do you want to play again?n

关于c - 两个问题,为什么双重打印以及如何重新开始! C编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27807460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com