gpt4 book ai didi

c - 奇怪的语句循环

转载 作者:行者123 更新时间:2023-11-30 19:35:08 24 4
gpt4 key购买 nike

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


//prototype
void input(int *);
void statements(int, int);
void print(int, int *);




void main()
{
int num, guess;
time_t t;

srand((unsigned) time(&t));
num=rand()% 100+1;

printf("%d\n", num);

input(&guess);
statements(num, guess);

}



void input(int *guess)
{
printf("Guess a number between 1 and 100: ");
scanf("%d", &*guess);
}

void statements (int num, int guess)
{


if(guess==num)
printf("You have guessed correct! The number is: %d", num);
else if(guess>num)
{
printf("The number you have guessed is too big\n");
print(num, &guess);

}
else if(guess<num)
{
printf("The number you have guessed is too small\n");
print(num, &guess);
}

}




void print( int num, int *guess)
{

printf("Guess again: ");
scanf("%d", &*guess);
statements(num, guess);
}

基本上,我正在为猜谜游戏编写一个程序作为作业,用户不断尝试,直到他/她的答案正确为止;但是,当我执行它时,如果用户第一次没有得到正确的结果,程序会一直告诉他数字太大,无论如何。不允许循环例子:85猜一个 1 到 100 之间的数字:90您猜到的数字太大再猜一下:20您猜到的数字太大再猜一下:

如有任何帮助,我们将不胜感激

最佳答案

除了评论指出的问题之外,您对递归的使用也是一个潜在的问题。如果用户一直猜测错误,最终将导致调用堆栈崩溃。另外,指针引用、取消引用的序列,即 &* 不会执行任何操作,因此您应该将其取出。因此,使用 while 循环而不是使用递归的正确代码如下所示:

void statements (int num, int guess)
{
while (guess!=num) {
if(guess>num) {
printf("The number you have guessed is too big\n");
print(num, &guess);
} else if(guess<num) {
printf("The number you have guessed is too small\n");
print(num, &guess);
}
}
printf("You have guessed correct! The number is: %d\n", num);
}

void print( int num, int *guess)
{
printf("Guess again: ");
scanf("%d", guess);
}

关于c - 奇怪的语句循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058955/

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