c - c 中的猜数字游戏,相同的猜测不会计算两次

标签 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;
}   

最佳答案

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

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/

相关文章:

c - 使用二叉搜索树进行井字棋(C)

c - C 中数组的最大索引大小是否为 2048?

java - 如果语句运算符被忽略?

ios - 试图将某些类型的用户路由到不同的主屏幕 Swift

javascript - PHP:如何根据数百个用户选项提供定制内容?

JavaScript if 语句

objective-c - 数学表达式评估 - 非常快 - 使用 objective-c

c - 以不规则速率存储二维数据

c - C 中的指针可以使用符号 [] 吗?

c# - 即使表中的列不允许为空,空文本框仍将数据保存在 SQL Server 中