Q: 格式%d和%i的差别是什么?
A: printf: 无差异; scanf: %i除了有%d的十进制输入功能外,还支持八进制和十六进制输入.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int n1, n2;
scanf("%d %i", &n1, &n2);
printf("%d %d\n", n1, n2);
return 0;
}
输入011 011:
%d: 011只被当做十进制,结果为11.
%i: 011可以当做八进制, 结果为9.
Q: C语言标准是如何规定%d和%i的?
A:
printf:
d,i The int argument is converted to signed decimal in the style [−]dddd. The
precision specifies the minimum number of digits to appear; if the value being
converted can be represented in fewer digits, it is expanded with leading zeros.
The default precision is 1. The result of converting a zero value with a precision
of zero is no characters.
scanf:
d Matches an optionally signed decimal integer, whose format is the same as
expected for the subject sequence of the strtol function with the value 10 for the
base argument. The corresponding argument shall be a pointer to signed integer.
i Matches an optionally signed integer, whose format is the same as expected
for the subject sequence of the strtol function with the value 0 for the base
argument. The corresponding argument shall be a pointer to signed integer.
对于scanf, %i和%d区别在于, %i可参考strtol(base为0, 可支持八进制/十进制/十六进制)转换, 而%d只支持base为10即十进制的转换.
Q: libc对于%d和%i有何区别?
A:
__vfprintf: %d和%i是相同处理.
https://opensource.apple.com/source/Libc/Libc-1272.250.1/stdio/FreeBSD/vfprintf.c.auto.html
__svfscanf: %i会置base为0, 后面base为0会根据实际数值转换成指定进制.
https://opensource.apple.com/source/Libc/Libc-1272.250.1/stdio/FreeBSD/vfscanf.c.auto.html
作者: 陈曦
环境: MacOS 10.14.5
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.6.0
转载请注明出处