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

解决方法

您认为问题可能是因为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;
}