请求printf()函数打印数据的指令要与打印数据的类型匹配. 例如, 打印整数时使用%d, 打印字符是使用%c. 这些符号被称为转换说明, 他们指定了数据转换称可显示的形式.
1. ANSI C标准为printf( )提供的转换说明
2. printf( )转换说明扩招修饰符
3. 补充转换说明修饰符的标记说明
4. 对于表格中的用例举例说明
4.1 使用修饰符和标记的示例
#include <stdio.h> #define PAGES 959 int main(int argc, const char * argv[]) { printf("*%d* ",PAGES); printf("*%2d* ",PAGES); printf("*%10d* ",PAGES); printf("*%-10d* ",PAGES); return 0; }
打印结果
*959* *959* * 959* *959 * Program ended with exit code: 0
4.2 浮点型格式
#include <stdio.h> #define PAGES 959 int main(int argc, const char * argv[]) { const double RENT = 3852.99; printf("*%f* ",RENT); printf("*%e* ",RENT); printf("*%4.2f* ",RENT); printf("*%3.1f* ",RENT); printf("*%12.3f* ",RENT); printf("*%12.3E* ",RENT); printf("*%+4.2f* ",RENT); printf("*%012.2f* ",RENT); return 0; }
打印结果
*3852.990000* *3.852990e+03* *3852.99* *3853.0* * 3852.990* * 3.853E+03* *+3852.99* *000003852.99* Program ended with exit code: 0
4.3 整数格式标记
#include <stdio.h> int main(int argc, const char * argv[]) { printf("%x %X %#x ",31,31,31); printf("**%d**% d**% d** ",42,42,-42); printf("**%5d**%5.3d**%05d**%05.3d** ",6,6,6,6); return 0; }
打印结果
1f 1F 0x1f **42** 42**-42** ** 6** 006**00006** 006** Program ended with exit code: 0
4.4 字符串打印格式
#include <stdio.h> #define STR "wuhan, I will come" int main(int argc, const char * argv[]) { printf("[%2s] ",STR); printf("[%24s] ",STR); printf("[%24.5s] ",STR); printf("[%-25.5s] ",STR); return 0; }
打印结果
[wuhan, I will come] [ wuhan, I will come] [ wuhan] [wuhan ] Program ended with exit code: 0