【问题标题】:Short is not working but int does?Short 不起作用,但 int 可以吗?
【发布时间】:2017-01-24 15:21:15
【问题描述】:
#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=10b=12c=13,它给出的输出是“c is small”?

当我用int 替换short 时,它会给出正确的输出。 我也尝试过%h%i,但输出相同。

怎么了?

【问题讨论】:

  • 这是 UB,您传递的是 short 而不是 int,这是 %d 格式说明符所期望的类型
  • 未定义的行为是未定义的。
  • 您是否假设shortint 的宽度相同?
  • 最简单的方法是打印程序读取的值,以确保程序读取的内容是您预期的。在您检查是否获得了scanf() 读取的三个值后添加printf("Data: a = %d, b = %d, c = %d\n", a, b, c);
  • 阅读scanf的文档和你使用的其他功能。还要启用编译器警告并注意它们。如果您的编译器无法检查scanf/printf 格式字符串,请使用现代编译器。

标签: c int short


【解决方案1】:

用途:

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

%d 用于int,其中%hi 用于short 数据类型

【讨论】:

  • 您还应该澄清为什么将 i 添加到格式说明符中。也许 OP 不希望这样。
  • 请注意,%hi 将接受 033 为 27,0x1B 也接受为 27。使用 %hd 将与使用 %d 的原始代码一致。
  • 更准确的说法是“%d 代表 int%hd 代表 short 数据类型”。事实上,%d%i 之间的区别与 intshort 无关。 h 修饰符对 short 很重要。
【解决方案2】:

下面的代码通过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;

顺便说一句:最好避免" %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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多