gpt4 book ai didi

c - 简单的猜谜游戏,允许用户在正确猜出随机数后再次玩?

转载 作者:行者123 更新时间:2023-11-30 17:04:01 25 4
gpt4 key购买 nike

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

int random_num;
void guessGame(int guessed_num){

char answer;
if (guessed_num == random_num){
printf("Correct! That's the number.\n");
printf("Would you like to play again (y or n)?\n");
scanf("%c", &answer);
if (answer=='y')
scanf("%d", &guessed_num);
guessGame(guessed_num);
if (answer=='n')
return 0;


}
else
if (guessed_num < random_num)
printf("Too low. Guess again.\n");
else
printf("Too high. Guess again.\n");
}

int main(){

int guessed_num = 0;
srand(time(NULL));
random_num = rand() % 50 + 1;

printf("I have a number between 1-50.\n");
printf("Can you guess what it is?\n");
printf("Enter your initial guess.\n");

while(1){

scanf("%d", &guessed_num);
guessGame(guessed_num);
}

return 0;
}

因此,在用户找到正确的随机数后,我希望他们能够再次玩游戏(如果他们愿意)。我该如何让代码重新运行?我尝试在我的guessGame 函数中执行此操作,但我知道这是错误的。

最佳答案

由于我的英语不好,我会给你代码(根据你的修改)。

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

int random_num;

int guessGame(int guessed_num) {


if (guessed_num == random_num) {
printf("Correct! That's the number.\n");
return 1;
} else if (guessed_num < random_num) {
printf("Too low. Guess again.\n");
return 0;
} else {
printf("Too high. Guess again.\n");
return 0;
}
}

int main() {
char loop;
while (1) {
int guessed_num = 0;
srand(time(NULL));
random_num = rand() % 50 + 1;
printf("I have a number between 1-50.\n");
printf("Can you guess what it is?\n");
printf("Enter your initial guess.\n");
while (1) {
scanf("%d", &guessed_num);
int returnValue = guessGame(guessed_num);
if (returnValue == 1) {
break;
}
}
printf("You wanna do it again? ");
getchar();
scanf("%c", &loop);
if (loop == 'n') {
break;
}
}
return 0;
}

关于c - 简单的猜谜游戏,允许用户在正确猜出随机数后再次玩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954018/

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