#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”的输出等于第一次和第二次的总和。如何解决问题?
例如,
第 1 次:9 次尝试
第二:8 次尝试
程序的输出显示了 17 次尝试而不是 8 次尝试。
最佳答案
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)
在进入 while
循环之前将 tries
设置为 0
:
num = rand() % 1000 + 1;
tries = 0;
while(guess != num)
关于c程序在循环程序时重复游戏的尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52503517/