2017-01-24 47 views
0
#include<stdio.h> 

int main() 
{ 
    short a, b, c; 
    printf("Enter the values of a, b and c: "); 
    scanf(" %d %d %d ", &a, &b, &c); 
    if(a<b && a<c) 
     printf("a is smaller"); 
    else if(b<a && b<c) 
     printf("b is smaller"); 
    else 
     printf("c is smaller"); 
    return 0; 
} 

對於輸入a=10,b=12,c=13,它給出輸出「c is smaller」?短不工作,但詮釋呢?

而當我用int替換short時,它會給出正確的輸出。 我也試過%h,%i但它輸出相同。

怎麼回事?

+13

這是UB,你是路過'short',而不是'int',即預期'%類型d'格式說明符 – LPs

+0

未定義的行爲未定義。 –

+2

你假設'short'和'int'是相同的寬度嗎? –

回答

2

使用:

scanf(" %hi %hi %hi ", &a , &b , &c); 

%dint,其中作爲%hishort數據類型

+1

而且您還應該澄清爲什麼您將** i **添加到格式說明符。也許OP不希望這樣。 – LPs

+1

請注意,'%hi'將接受'033'爲27,'0x1B'也爲27.使用'%hd'將與使用'%d'的原始代碼一致。 –

+1

更準確的說法是「'%d'是'int',而'%hd'是'short'數據類型」。實際上,'%d'和'%i'之間的區別與'int'和'short'沒有任何關係。這是'h'修飾符對'short'很重要。 –

0

在下面的代碼經過short *,但scanf("%d...期望一個int *。使用錯誤的說明符/類型匹配結果未定義的行爲

你的編譯器應該已經警告過這個問題。 @Olaf

short a; 
scanf("%d", &a); // wrong type 

而是使用h修飾符來指示short *

scanf("%hd", &a); 

如果您使用的是舊編譯,即缺乏h修改,讀爲int,然後分配。

int t; 
scanf("%d", &t); 
a = t; 

BTW:最好避免在尾部空間" %d %d %d "

// Avoid last space 
// scanf(" %d %d %d ", &a, &b, &c); 

scanf("%hd %hd %hd", &a, &b, &c); 
// or the following which does the same 
scanf("%hd%hd%hd", &a, &b, &c);