如何填充printf以考虑负号和可变长度数字? [英] How do I pad a printf to take account of negative signs and variable length numbers?

查看:99
本文介绍了如何填充printf以考虑负号和可变长度数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在日志文件中输出一些数字,并且我想通过printf函数填充一些浮点数以产生:

I'm trying to output some numbers in a log file and I want to pad a load of floats via the printf function to produce:

 058.0
 020.0
 038.0
-050.0
 800.0
 150.0
 100.0

目前我正在这样做:

printf("% 03.1f\n", myVar);

...其中myVar是浮点数.该语句的输出如下所示:

...where myVar is a float. The output from that statement looks like this:

58.0
20.0
38.0
-50.0
800.0
150.0
100.0

我已阅读的内容中,我希望我的代码能够产生我在这篇文章的开头提到的输出,但是显然有些地方出了问题.您一次只能使用一个标志吗? ..或者这里还有其他事情吗?

From what I've read I would expect my code to produce the output I mentioned at the top of this post, but clearly something is wrong. Can you only use one flag at a time? ..or is there something else going on here?

推荐答案

宽度说明符是完整宽度:

The width specifier is the complete width:

printf("%05.1f\n", myVar);  // Total width 5, pad with 0, one digit after .

要获得所需的格式,请执行以下操作:

To get your expected format:

printf("% 06.1f\n", myVar);

这篇关于如何填充printf以考虑负号和可变长度数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆