簡體   English   中英

為什么我的C程序在不同的編譯器中提供不同的輸出?

[英]Why does my C program give different outputs in different compilers?

我的程序的結果不是我所期望的,並且在不同的編譯器上有所不同。

我在三個編譯器上嘗試過,其中兩個編譯器得到相同的結果。 但我想要兩個結果的組合。

#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的情況下,我們總是有正確的答案。 這發生在兩個在線編譯器中。 但是在clang中,當我這樣做並且不起作用時。 isdigit函數不起作用

使用%d格式說明符,您將int讀入iUserInput 這是正確的,但是你使用isdigit試着看看數字是否在110之間。 但是,此功能用於查明char是否介於'0''9' 這是不一樣的 - 假設ASCII這些字符分別等於4857 所以你isdigit檢查最有可能發現輸入的號碼是否與4857 (雖然沒有保證的ASCII使用,所以不同的編碼可能導致不同的結果)。

相反,檢查應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM