首页 > 解决方案 > 为什么我的 C 程序在不同的编译器中给出不同的输出?

问题描述

我的程序的结果不是我所期望的,并且在不同的编译器上是不同的。

我已经在三个编译器上进行了尝试,其中两个给出了相同的结果。但我想要两个结果的组合。

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

int main()
{
    int iRandomNum = 0;
    int iUserInput = 0;
    const int VIP = 7;
    srand(time(NULL));
    iRandomNum = (rand() % 10) + 1;

    printf("\nGuess a number between 1 to 10.\n Make a wish and type in the number.\n");

    scanf("%d", &iUserInput);

    if(isdigit(iUserInput))
    {
         printf("\n\nYou did not enter a digit between 1 to 10.\n\n");
    }
    else
    {
        if(iUserInput==iRandomNum || iUserInput==VIP)
            printf("\n\nYou guessed it right!\n\n\n");
        else
            printf("\n\nSorry the right answer was %d.\n\n\n", iRandomNum);
    }
    return 0;
}

当我选择任何数字时,如果我在这个猜数字游戏中没有选择正确的数字,程序只会提醒我。但是在 7 的情况下,我们总是有正确的答案。这发生在两个在线编译器中。但是在铿锵声中,当我这样做时,它不起作用。然后 isdigit 函数不起作用

标签: cnumbers

解决方案


使用%d格式说明符,您正在读取intinto iUserInput。那是正确的,但是您使用它isdigit来尝试查看数字是否在1和之间10。但是,此函数用于确定 achar是否在'0'和之间'9'。这不一样 - 假设 ASCII 这些字符分别等于4857。因此,您isdigit很可能会检查输入的数字是否介于48和之间57(尽管不能保证使用 ASCII,因此不同的编码可能会导致不同的结果)。

相反,检查应该是:

if((iUserInput >= 1) && (iUserInput <= 10)) {...}

推荐阅读