我正在编写一个代码,其中涉及用户猜测 1 到 20 之间的数字,但它会计算每次猜测,包括重复的数字。我怎样才能编辑它,以便它只计算每个猜到一次的数字?这是我到目前为止所拥有的:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int r = rand() %20 + 1;
int guess;
int correct = 0;
int count = 0;
printf("Let's play a number guessing game!\n");
printf("Guess a number between 1 and 20.\n");
do
{
scanf("%d", &guess);
if (guess == r)
{
count++;
printf("Congrats! you guessed the right answer in %d attempts!\n", count);
correct = 1;
}
if (guess < r)
{
count++;
printf("Too low, try again.\n");
}
if (guess > r)
{
count++;
printf("Too high, try again.\n");
}
}
while (correct == 0);
return 0;
}
最佳答案
您可以使用查找表来检测数字是否重复:
int used[21] = {0};
do
{
scanf("%d", &guess)
if (guess < 1 || guess > 20) {
puts("pssst ... from 1 to 20");
continue;
}
if (used[guess] == 1) {
puts("Repeated!");
continue; /* without counting */
} else {
used[guess] = 1;
}
...
关于c - c 中的猜数字游戏,相同的猜测不会计算两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42103410/