#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int num;
int guess = 0;
int response = 1;
int tries = 0;
srand(time(0));
while (response == 1)
{
printf("Please type your first guess.\n");
num = rand() % 1000 + 1;
while (guess != num)
{
scanf("%d", &guess);
tries = tries + 1;
if (guess == num)
{
printf("good job\n");
}
else if (guess > num)
{
printf("too high, try again\n");
}
else
{
printf("too low, try again\n");
}
}
printf("Guess Taken = %d\n", tries);
printf ("Would you like to play again? \n");
printf("Please type ( 1=yes, 2=no ) ");
scanf ("%d", &response);
}
system("pause");
return 0;
}
第二次运行该程序的“ Guess Taken”的输出等于第一次和第二次的总和。如何解决问题?
例如,
第一次:9次尝试
第二:8次尝试
程序的输出显示了17次尝试,而不是8次尝试。
答案 0 :(得分:1)
printf("I have a number between 1 and 1000.\n" "Can you guess my number?\n" "Please type your first guess.\n"); num = rand() % 1000 + 1; while(guess != num)
在进入tries
循环之前,将0
设置为while
:
num = rand() % 1000 + 1;
tries = 0;
while(guess != num)
答案 1 :(得分:1)
在每次游戏之后,您都不会将变量tries
重置为零。如果您将tries = 0;
放在第一个while循环之后,那么它应该可以工作。