我该如何调整一些像在C? [英] How do I align a number like this in C?

查看:141
本文介绍了我该如何调整一些像在C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调整一系列的数字在C中是的printf()这样的例子:

I need to align a series of numbers in C with printf() like this example:

-------1
-------5
------50
-----100
----1000

当然,还有所有那些之间的数字,但它是不相关的手头的问题...呵呵,考虑破折号空格,我用破折号所以很容易理解我想要什么。

Of course, there are numbers between all those but it's not relevant for the issue at hand... Oh, consider the dashes as spaces, I used dashes so it was easier to understand what I want.

我唯一能够做到这一点:

I'm only able to do this:

----1---
----5---
----50--
----100-
----1000

或者这样:

---1
---5
--50
-100
1000

不过,这一切都不是我想要的,我不能做到什么,只使用printf()的显示在第一个例子。是否有可能呢?

But none of this is what I want and I can't achieve what is displayed on the first example using only printf(). Is it possible at all?

编辑:
对不起的人,我很着急,并没有解释自己好......我最后的例子,您的建议(使用类似%8D),千万不要因为工作,虽然最后一个数字是1000不一路一定去1000甚至100或10的这一问题。


Sorry people, I was in a hurry and didn't explain myself well... My last example and all your suggestions (to use something like "%8d") do not work because, although the last number is 1000 it doesn't necessarily go all the way to 1000 or even 100 or 10 for that matter.

无论是要显示的数字号码,我只想4最多人数最多的前导空格。比方说,我要显示从1位数到1000(A)和1〜100(B)我用,为%4D,这将是输出:

No matter the number of digits to be displayed, I only want 4 leading spaces at most for the largest number. Let's say I have to display digits from 1 to 1000 (A) and 1 to 100 (B) and I use, for both, "%4d", this would be the output:

答:

---1
....
1000

这是我想要的输出...

Which is the output I want...

B:

---1
....
-100

这是不是我想要的输出,其实我是想这样的:

Which is not the output I want, I actually want this:

--1
...
100

但就像我说的,我不知道我必须打印号码的确切数字,它可以有1个数字,它可以有2个,3个或更多,功能应该是ppared所有$ P $。我想四个额外的附加前导空格但是这并不重要。

But like I said, I don't know the exact number of numbers I have to print, it can have 1 digit, it can have 2, 3 or more, the function should be prepared for all. And I want four extra additional leading spaces but that's not that relevant.

编辑2: 看来,我想要什么,我需要的方式,这是不可能的(检查戴维·索恩利和空白泽维尔答案和我的意见)。谢谢大家的宝贵时间。

EDIT 2: It seems that what I want, the way I need it, it's not possible (check David Thornley and Blank Xavier answers and my comments). Thank you all for your time.

推荐答案

看这件事在我方便的哈比森和放大器;斯蒂尔....

Looking this up in my handy Harbison & Steele....

确定字段的最大宽度。

int max_width, value_to_print;
max_width = 8;
value_to_print = 1000;
printf("%*d\n", max_width, value_to_print);

记住,max_width的类型必须为 INT 与星号的工作,你就会有计算它的基础上有多少空间,你要想拥有。在你的情况,你必须计算出最大数量的最大宽度,并添加4。

Bear in mind that max_width must be of type int to work with the asterisk, and you'll have to calculate it based on how much space you're going to want to have. In your case, you'll have to calculate the maximum width of the largest number, and add 4.

这篇关于我该如何调整一些像在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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