小小的疑问,求解#include stdio.hint main(){ short int a0xffff printf(a%x\n,a) return 0}shor
小小的疑问,求解
#include <stdio.h>
int main()
{
short int a=0xffff;
printf("a=%x\n",a);
return 0;
}
short int 在内存中占2个字节,为什么以上输出为ffffffff,哪位大虾可否告知,谢谢
[解决办法]
发生了类型提升。
[解决办法]
%x, 无符号的16进制数字,并以小写abcdef表示,
这样打印的时候会自动进行类型提升,所以打印出ffffffff
应该用%hx,
printf("a=%hx\n",a);[解决办法]LS正解,类型提升
[解决办法]向上提升分有符号扩展和无符号扩展,这里是有符号扩展。
[解决办法]printf里面的%和变量的一一对应关系
scanf里面的%和变量以及变量前加不加&的一一对应关系
是C代码中非常容易出错的地方,而且通常编译还不出错。
所以在编译源代码之前值得专门仔细检查一遍甚至多遍。
Size and Distance Specification
The optional prefixes to type, h, l, and L, specify the “size” of argument (long or short, single-byte character or wide character, depending upon the type specifier that they modify). These type-specifier prefixes are used with type characters in printf functions or wprintf functions to specify interpretation of arguments, as shown in the following table. These prefixes are Microsoft extensions and are not ANSI-compatible.
Table R.6 Size Prefixes for printf and wprintf Format-Type Specifiers
To Specify Use Prefix With Type Specifier
long int l d, i, o, x, or X
long unsigned int l u
short int h d, i, o, x, or X
short unsigned int h u
__int64 I64 d, i, o, u, x, or X
Single-byte character with printf functions h c or C
Single-byte character with wprintf functions h c or C
Wide character with printf functions l c or C
Wide character with wprintf functions l c or C
Single-byte – character string with printf functions h s or S
Single-byte – character string with wprintf functions h s or S
Wide-character string with printf functions l s or S
Wide-character string with wprintf functions l s or S
Thus to print single-byte or wide-characters with printf functions and wprintf functions, use format specifiers as follows.
To Print Character As Use Function With Format Specifier
single byte printf c, hc, or hC
single byte wprintf C, hc, or hC
wide wprintf c, lc, or lC
wide printf C, lc, or lC
To print strings with printf functions and wprintf functions, use the prefixes h and l analogously with format type-specifiers s and S.