我已经为猜谜游戏运行了两组测试范围,1)1 到 100 和 2)50 到 90。
第一组给出了正确的输出,但我的第二个测试范围仅作为结果输出“太高”,因为它应该运行 8 个值太低,第九个值太高,然后在 10 日正确猜测尝试。
这是我的代码,非常感谢任何帮助,谢谢!
版本 1
原始代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int min, max, number, guess, count = 0;
printf("Please enter two integers for the range:\n");
scanf("%d %d", &min, &max);
number = (min + rand()%(max - min + 1));
printf("I'm thinking of a number between %d and %d.\n", min, max);
printf("Enter your guess:\n");
scanf("%d", &guess);
while(guess != number)
{
if(guess < number)
{
count++;
printf("Too low.\n");
printf("Enter your guess:\n");
scanf("%d", &guess);
}
else
{
count++;
printf("Too high.\n");
printf("Enter your guess:\n");
scanf("%d", &guess);
}
}
count++;
printf("Correct, it took you %d tries to guess my number. ", count);
return 0;
}
版本 2
根据答案的反馈修改代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int min, max, number, guess, count = 0;
printf("Please enter two integers for the range:\n");
scanf("%d %d", &min, &max);
srand(time(NULL));
number = (min + rand()%(max - min + 1));
printf("I'm thinking of a number between %d and %d.\n", min, max);
scanf("%d", &guess);
do
{
printf("Enter your guess:\n");
scanf("%d", &guess);
if ( guess < number)
{
printf("Too low.\n");
}
else if ( guess > number)
{
printf("Too high.\n");
}
}
while (guess != number && count++);
count++;
printf("Correct, it took you %d tries to guess my number. ", count);
return 0;
}