#include
#include
int main()
{
int a = 2;
int b = -32;
char c = -32;
int d = 108;
char *e = "hello world";
int f = 'f';
double g = 3.14159;
double h = 123456789;
double pi = 4 * atan(1.0);
// ansi add
int *p = &a;
int n;
printf("a = %d\n", a);
printf("b = %u\n", b);
printf("c = %u\n", c);
printf("The value d = 108: decimal = %d, octal = %o, hex = %x, upper hex = %X\n", d, d, d, d);
printf("%s\n", e);
printf("%c\n", f);
printf("%g, %g, %g, %g, %g\n", 1/1.0, 1/2.0, 1/3.0, 1/4.0, 0.0);
printf("%g\n", g);
printf("%e, %E\n", g, g);
printf("%G\n", h);
printf("%%d\n");
printf("%2d,%2d*\n", a, d);
printf("%.2d,%.2d*\n", a, d);
printf("%.0f,%.2f,%.6f,%.10f\n", pi, pi, pi, pi, pi);
printf("%.0e,%.1e,%.2e,%.10e\n", pi, pi, pi, pi);
printf("the address a = %p\n", p);
printf("hello\n%n", &n);
printf("n = %d\n", n);
return 0;
}
测试结果:
cheny.le@cheny-ThinkPad-T420:~$ ./a.out
a = 2
b = 4294967264
c = 4294967264
The value d = 108: decimal = 108, octal = 154, hex = 6c, upper hex = 6C
hello world
f
1, 0.5, 0.333333, 0.25, 0
3.14159
3.141590e+00, 3.141590E+00
1.23457E+08
%d
2,108*
02,108*
3,3.14,3.141593,3.1415926536
3e+00,3.1e+00,3.14e+00,3.1415926536e+00
the address a = 0x7fff161928c8
hello
n = 6
大致解释一下:
格式码:
(1)%d,以十进制的方式打印符号整型
(2)%u,以十进制的方式打印无符号整型,负数会打印成一个很大的整数
(3)%o,以八进制的方式打印整型
(4)%x和%X,分别以小写和大写的十六进制方式打印整型
(5)%s,打印字符串,以\0结束打印
(6)%c,打印ascii 字符
(7)%g,打印浮点值,会去掉数值围缀的0,保留6位有效数字,当值大于999999的时候会以科学计数法打印
(8)%e,强制以指数的形式打印浮点数
(9)%f,进制以指数的形式打印浮点数
(10)%p,打印指针(ansi c增加)
(11)%n,传递一个指向整型的指针,该指针指向的地址存储打印的字符数
修饰符:
(1)%ld,%lu,%lo,%lx,带l修饰的格式码要求long型整数作为其对应参数
(2)%2d则是宽度修饰符,作用是制定它所修饰的格式项所对应打印的字符数,如果带打印的数值不能填满位置,则左侧会被补上空格字符以使这个字符数值的宽度满足要求,如果太大则输入宽度会适当调整以满足需要
(3).%2d同样是宽度修饰符,不同的是如果不能填满位置则在前面补上0,如果太大则会四舍五入满足需求,不会调整宽度