我仍然掌握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("nGoodbyen");
}
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("nt*******************************************");
printf("nt* Wow you guessed it! Yep its %d alright. *", num);
printf("nt* You won't get it next time! :) *");
printf("nt*******************************************");
}
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;
}
更改wrong
以使用指针参数guess
为
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);
}
}
这允许您的外部guess
变量值更改wrong