#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL)); // initiates random number generation
int CpuGuess;
int IsCorrect;
int HigherLower;
int lower,higher;
printf("Think of a number from 1-9, keep it in mind.n");
CpuGuess = rand() % 10; //cpu guesses number between 1-9
printf("Is your number %d? Yes = 1, No = 2, Enter here: ", CpuGuess);
scanf("%d",&IsCorrect); // asks if its 1 or 2 depending if correct or false
while(IsCorrect == 2)
{
printf("Is your number higher or lower?, lower = 1, higher = 2");
scanf("%d",&HigherLower);
if(HigherLower==1)
{
lower == 0;
higher = CpuGuess;
CpuGuess = (rand() % (higher - lower+1)) + lower;
printf("Is your number %d?", CpuGuess);
}
else if(HigherLower==2)
{
}
}
if(IsCorrect == 1)
{
printf("I have guessed your number!");
}
}
无法在上限和下限之间猜测,它猜测的数字很荒谬,比如460之类的,我越说低,它就会下降,但只会下降到某一点,每次都不同(仍然是400+)
所以我已经评论过了,问题似乎是与lower == 0
。这是一个比较,而不是赋值,所以在这一点上,lower
变量从未初始化,因此,如果你执行CpuGuess = (rand() % (higher - lower+1)) + lower;
,较低的变量会创建未定义的行为,因为我们不知道该变量实际具有什么值。
简单的修复是改变lower == 0;
为lower = 0;
,它应该工作良好。