猜猜c中的数字游戏,它没有计算两次相同的猜测

时间:2017-02-08 02:01:43

标签: c if-statement

我正在处理一个代码,该代码涉及用户猜测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;
}   

1 个答案:

答案 0 :(得分:1)

您可以使用查找表来检测是否重复了一个数字:

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;
    }
    ...