c语言printf修饰符及作用,printf()使用修饰符和标志

标志

含义

-

该项目是左对齐的; 也就是说,它从字段的左侧开始打印。 示例:“%- 20s”。

+

如果为正,则带符号值显示加号,如果为负,则带有减号。 示例:“%+ 6.2f”。

如果为正,则显示带有前导空格(但没有符号)的带符号值,如果为负,则带有减号。 A+标志覆盖空格。 示例:“%6.2f”。

#

使用替代形式进行转换规范。 示例:“%#o”,“%#8.0f”和“%+#10.3E”。

0

对于数字形式,使用前导零填充字段宽度而不是空格。 示例:“%010d”和“%08.3f”。

使用修饰符和标志的示例

#include

#define PAGES 959

int main(void)

{

printf("*%d*\n", PAGES);

printf("*%2d*\n", PAGES);

printf("*%10d*\n", PAGES);

printf("*%-10d*\n", PAGES);

return 0;

}

执行上面示例代码,得到以下结果:

$gcc -o main *.c

$main

*959*

*959*

* 959*

*959 *

一些浮点数的组合:

#include

int main(void){

const double RENT = 3852.99; // const-style constant

//

printf("*%f*\n", RENT);

printf("*%e*\n", RENT);

printf("*%4.2f*\n", RENT);

printf("*%3.1f*\n", RENT);

printf("*%10.3f*\n", RENT);

printf("*%10.3E*\n", RENT);

printf("*%+4.2f*\n", RENT);

printf("*%010.2f*\n", RENT);

return 0;

}

执行上面示例代码,得到以下结果:

$gcc -o main *.c

$main

*3852.990000*

*3.852990e+03*

*3852.99*

*3853.0*

* 3852.990*

* 3.853E+03*

*+3852.99*

*0003852.99*

一些格式标记的说明

#include

int main(void)

{

printf("%x %X %#x\n", 31, 31, 31);

printf("**%d**% d**% d**\n", 42, 42, -42);

printf("**%5d**%5.3d**%05d**%05.3d**\n", 6, 6, 6, 6);

return 0;

}

执行上面示例代码,得到以下结果:

$gcc -o main *.c

$main

1f 1F 0x1f

**42** 42**-42**

** 6** 006**00006** 006**

字符串格式示例:

#include

#define BLURB "Authentic imitation!"

int main(void)

{

printf("[%2s]\n", BLURB);

printf("[%24s]\n", BLURB);

printf("[%24.5s]\n", BLURB);

printf("[%-24.5s]\n", BLURB);

return 0;

}

执行上面示例代码,得到以下结果:

$gcc -o main *.c

$main

[Authentic imitation!]

[ Authentic imitation!]

[ Authe]

[Authe ]

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值