首页 > 解决方案 > C语言中的猜谜游戏

问题描述

我使用 while 循环在 C 编程中构建了一个猜谜游戏,但在执行过程中遇到了问题。因此,当我打印一个小于猜测数或大于猜测数的数字时,我会得到正确答案。但是当用户输入正确答案时,屏幕会显示更大数字的语句“您输入的数字大于密码”。然后它在“这是秘密号码”下方显示正确的声明。我认为问题可能是因为 else 语句没有定义更大数量的条件,但我不知道如何解决这个问题。有人可以帮助我吗?

#include <stdio.h>
#include <stdlib.h>
    
    int main()
    {
        //Guessing game
        const int SecretNum = 4;
        int guess;
        while (guess != SecretNum){
                printf("Enter a number: ");
                scanf("%d", &guess);
                if (guess < SecretNum){
            printf("The number you entered is less than the Secret Number. \n");
                } else printf("The number you entered is greater than the Secret Number.\n");
                }
          printf("This is the secret number.\n");
    return 0;
    }

标签: c

解决方案


您认为问题可能是因为 else 语句没有定义更大数字的条件,所以您应该添加它。

guess此外,您必须在使用其值之前进行初始化。

正确使用缩进格式化代码是另一个重要部分。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Guessing game
    const int SecretNum = 4;
    int guess = !SecretNum; /* initialize guess : guess will be different value from SecretNum using this */
    while (guess != SecretNum){
        printf("Enter a number: ");
        scanf("%d", &guess);
        if (guess < SecretNum){
            printf("The number you entered is less than the Secret Number. \n");
        } else if (guess > SecretNum) /* add condition */
            printf("The number you entered is greater than the Secret Number.\n");
    }
    printf("This is the secret number.\n");
    return 0;
}

推荐阅读