参考博客:https://blog.csdn.net/sinat_34009734/article/details/51646469
printf格式输出:%[flags][width][.perc][F|N|h|l]type
用到了flags中的 0 (注意是零不是欧) ,其百科描述为:将输出的前面补上0,直到占满指定列宽为止(不可以搭配使用-)
width 即表示需要输出的位数。
- int a = 4;
- printf("%03d",a);
输出:004
也可以用 * 代替位数,在后面的参数列表中用变量控制输出位数;
- int a
= 4;
- int n
= 3;
- printf("%0*d",n,a);
输出:004
如:
int main()
{
char c, s[20];
int a=1234;
float f=3.141592653589;
double x=0.12345678912345678;
strcpy(s, "Hello,World");
c='x41';
printf("a=%d ", a);//按照十进制整数格式输出,显示 a=1234
printf("a=%d%% ", a);//输出%号 结果 a=1234%
printf("a=%6d ", a);//输出6位十进制整数 左边补空格,显示 a= 1234
printf("a=%06d ", a);//输出6位十进制整数 左边补0,显示 a=001234
printf("a=%2d ", a);//a超过2位,按实际输出 a=1234
printf("a=%-6d ", a);///输出6位十进制整数 右边补空格,显示 a=1234
printf("f=%f ", f);//浮点数有效数字是7位,结果 f=3.141593
printf("f=6.4f ", f);//输出6列,小数点后4位,结果 f=3.1416
printf("x=%lf ", x);//输出长浮点数 x=0.123457
printf("x=%18.16lf ", x);//输出18列,小数点后16位,x=0.1234567891234567
printf("c=%c ", c); //输出字符 c=A
printf("c=%x ", c);//以十六进制输出字符的ASCII码 c=41
printf("s[]=%s ", s);//输出数组字符串s[]=Hello,World
printf("s[]=%6.9s ", s);//输出最多9个字符的字符串 s[]=Hello,Wor
int a=1234;
float f=3.141592653589;
double x=0.12345678912345678;
strcpy(s, "Hello,World");
c='x41';
printf("a=%d ", a);//按照十进制整数格式输出,显示 a=1234
printf("a=%d%% ", a);//输出%号 结果 a=1234%
printf("a=%6d ", a);//输出6位十进制整数 左边补空格,显示 a= 1234
printf("a=%06d ", a);//输出6位十进制整数 左边补0,显示 a=001234
printf("a=%2d ", a);//a超过2位,按实际输出 a=1234
printf("a=%-6d ", a);///输出6位十进制整数 右边补空格,显示 a=1234
printf("f=%f ", f);//浮点数有效数字是7位,结果 f=3.141593
printf("f=6.4f ", f);//输出6列,小数点后4位,结果 f=3.1416
printf("x=%lf ", x);//输出长浮点数 x=0.123457
printf("x=%18.16lf ", x);//输出18列,小数点后16位,x=0.1234567891234567
printf("c=%c ", c); //输出字符 c=A
printf("c=%x ", c);//以十六进制输出字符的ASCII码 c=41
printf("s[]=%s ", s);//输出数组字符串s[]=Hello,World
printf("s[]=%6.9s ", s);//输出最多9个字符的字符串 s[]=Hello,Wor
return 0;
}