C语言中%d和%i格式说明符之间的差异

x33g5p2x  于2021-09-19 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(435)

由百分比符号 (%) 形成的序列表示格式说明符,用于指定要从流中检索并存储到附加参数所指位置的数据的类型和格式。简而言之,它告诉我们要存储哪种类型的数据以及要打印哪种类型的数据。
    示例:如果要使用 scanf() 和 printf() 函数读取和打印整数,则使用 %i 或 %d,但在 %i 和 %d 格式说明符中存在细微差别。

%d 指定有符号十进制整数,%i 指定整数
在 printf 中,%d 和 %i 的行为相同

printf 的 %i 和 %d 格式说明符之间没有区别。考虑以下示例。

// C program to demonstrate
// the behavior of %i and %d
// with printf statement
#include <stdio.h>

int main()
{
	int num = 9;
	
	// print value using %d
	printf("Value of num using %%d is = %d\n", num);
	
	// print value using %i
	printf("Value of num using %%i is = %i\n", num);

	return 0;
}

输出:

Output:
Value of num using %d is = 9
Value of num using %i is = 9
在 scanf 中,%d 和 %i 的行为不同

%d 假设基数为10,而 %i 自动检测基数。因此,两个说明符在与输入说明符一起使用时的行为不同。对 %i 而言,012是10;对 %d 而言,012就是12。
    %d 取整数值作为有符号十进制整数。它接受负值和正值,但值应为十进制,否则将打印垃圾值。(注意:如果输入是八进制格式,如012,那么 %d 将忽略 0 并将输入视为 12)考虑以下示例。
    %i 取十进制、十六进制或八进制类型的整数值。要输入十六进制格式的值 - 值前面应添加“0x”,输入八进制格式的值 - 值前面应添加“0”。
    考虑下面的例子。

// C program to demonstrate the difference
// between %i and %d specifier
#include <stdio.h>

int main()
{
	int a, b, c;

	printf("Enter value of a in decimal format:");
	scanf("%d", &a);

	printf("Enter value of b in octal format: ");
	scanf("%i", &b);

	printf("Enter value of c in hexadecimal format: ");
	scanf("%i", &c);

	printf("a = %i, b = %i, c = %i", a, b, c);

	return 0;
}

输出:

Output:
Enter value of a in decimal format:12
Enter value of b in octal format: 012
Enter value of c in hexadecimal format: 0x12
a = 12, b = 10, c = 18

说明:
    八进制的12,转换为十进制值是10
    十六进制的12,转换为十进制值是18

参考文档

[1]Shubham Bansal.Difference between %d and %i format specifier in C language[EB/OL].https://www.geeksforgeeks.org/difference-d-format-specifier-c-language/,2021-02-19.

相关文章