2017-01-24 49 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);