gpt4 book ai didi

C While循环编译但不工作问题

转载 作者:行者123 更新时间:2023-11-30 15:37:42 24 4
gpt4 key购买 nike

我仍在掌握 C 循环的窍门。我不明白为什么我的 while 循环不起作用。

我在这个程序中没有收到任何错误,但发生的情况是 while 循环正在执行 else if 语句,并且不会返回到 >if 语句。但如果您在第一次猜测时输入了正确的数字,它就会执行 if。当您在第一次猜测后的任何时间尝试猜测时,它不会运行完整的 while 循环并继续显示数字“太低”。我究竟做错了什么?我该如何解决它?

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

int ranNumGen();
void Right(int num); // prompt that you guessed right
void wrong(int guess, int num); // if else's to tell you to high to low...
void sorry(int num); // prompt for not guessing it right


int main(void)
{
// Local declarations
int num;
int guess;
int a;

// Sets variables
num = ranNumGen();
a = 0;


// Prompt
printf("\nLets play a game");
printf("\nCan you guess the number I am thinking of?");
printf("\nI will give you a hint its a number between (1 and 20)");
printf("\nI am also going to going to give you five tries.");
printf("\nHave a guess! ");
printf("Shows number to win %d", num); // shows number to win to check if it works
scanf_s("%d", &guess);




while (a < 4)
{
(a++);

if (guess == num)
{
Right(num);
break;
}
else if (guess < num || guess > num)
{
wrong(guess, num);
}
}


// End promts
if (guess == num)
{
printf("\nGoodbye\n");
}
else
{
sorry(num);
}
return 0;
}

int ranNumGen()
{
int range;
srand(time(NULL));
range = 20;
range = (rand() % range + 10) + 1;
return range;
}

void Right(int num)
{
printf("\n\t*******************************************");
printf("\n\t* Wow you guessed it! Yep its %d alright. *", num);
printf("\n\t* You won't get it next time! :) *");
printf("\n\t*******************************************");
}

void wrong(int guess, int num)
{
if (guess > num)
{
printf("\nYour guess is to high.", guess);
printf("\nTry again: ");
scanf_s("%d", &guess);
}
else if (guess < num)
{
printf("\nYour guess is to low.", guess);
printf("\nTry again: ");
scanf_s("%d", &guess);
}
}

void sorry(int num)
{
printf("\nSorry buddy, you didn't guess it...");
printf("\nThe number was %d better luck next time.\n", num);
return;
}

最佳答案

更改错误以使用指针参数进行猜测

void wrong(int *guess, int num)
{
if ((*guess) > num)
{
printf("\nYour guess is to high.", *guess);
printf("\nTry again: ");
scanf_s("%d", guess);
}
else if ((*guess) < num)
{
printf("\nYour guess is to low.", *guess);
printf("\nTry again: ");
scanf_s("%d", guess);
}
}

这允许您的外部猜测变量值被错误更改

关于C While循环编译但不工作问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122526/

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