%d %i的区别(你想知道的C语言 2.3)

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
 
转载请注明出处

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值