C中的格式说明符
时间:2020-02-23 14:32:03 来源:igfitidea点击:
C语言中的格式说明符用于接受数据并向用户显示数据。
用编程术语来说,格式说明符可帮助编译器分析提供给程序的数据类型。
因此,它有助于找出与程序的相应变量关联的数据类型。
要记住的要点:
基本上,有三个元素主导着格式说明符:
句点(.)–分隔字段宽度并提供精度。
减号(-)–提供左对齐。
在"%"之后的数字,用于指定要打印的字符串的最小宽度。
C格式说明符列表
| Format Specifier | Description |
|---|---|
| %c | Accepts and prints characters |
| %d | Accepts and prints signed integer |
| %e or %E | Scientific notation of floats |
| %f | Accepts and prints float numbers |
| %hi | Prints the signed integer |
| %hu | Prints unsigned integer |
| %i | Accepts and prints integer values |
| %l or %ld or %li | Long integer values |
| %lf | Double values |
| %Lf | Long double values |
| %lu | Unsigned int or unsigned long |
| %o | Provides the octal form of representation |
| %s | Accepts and prints String values |
| %u | Accepts and prints unsigned int |
| %x or %X | Provides the hexadecimal form of representation |
| %n | Provides a new line |
| %% | This prints % character |
整数格式说明符(%d或者%i或者%u)
整数格式说明符通过程序接受并打印整数值。
例:
#include <stdio.h>
int main()
{
int x = 0;
printf("Enter the value of x:\n");
scanf("%d", &x);
printf("%d\n", x);
int z = 0;
printf("Enter the value of z:\n");
scanf("%i", &z);
printf("%i\n", z);
return 0;
}
输出:
Enter the value of x: 10 10 Enter the value of z: 25 25
"%d"格式说明符将输入数字以十进制格式表示,而"%i"格式说明符将输入数字以十进制或者八进制或者十六进制格式表示。
字符格式说明符(%c)
字符格式说明符接受并通过程序打印字符值。
例:
#include <stdio.h>
int main()
{
char x = "";
printf("Enter the character:\n");
scanf("%c", &x);
printf("The entered character is:\n");
printf("%c\n", x);
return 0;
}
输出:
Enter the character: D The entered character is: D
八进制格式说明符(%o)
八进制格式说明符有助于提供给定整数的八进制表示形式。
例:
#include <stdio.h>
int main()
{
int num = 69;
printf("The octal form of the input:\n");
printf("%o\n", num);
return 0;
}
输出:
The octal form of the input: 105
浮点格式说明符(%f或者%e或者%E)
例:
#include <stdio.h>
int main()
{
float num = 1.24578;
printf("%f\n", num);
printf("%0.2f\n", num);
printf("%e\n", num);
return 0;
}
在上面的代码中,%0.2f提供了最多两个十进制值的精度。
输出:
1.245780 1.25 1.245780e+00
十六进制格式说明符(%x或者%X)
十六进制格式说明符提供给定整数的十六进制表示形式。
例:
#include <stdio.h>
int main()
{
int num = 13;
printf("%x\n", num);
return 0;
}
输出:
d
字符串格式说明符(%s)
这些格式说明符通过程序接受并打印字符数组或者字符串。
例:
#include <stdio.h>
int main()
{
char in_str[] = "Engineering Discipline";
printf("%s\n", in_str);
return 0;
}
输出:
Engineering Discipline

