简体   繁体   English

格式化printf

[英]Formatting for printf

I was given a problem where I was supposed to find factorals of numbers 1 - 20. That I completed, but in the example I was given the console if formatted to be visually appealing. 我遇到了一个问题,我应该找到数字1到20的阶乘。我完成了,但是在示例中,我将控制台的格式设置为具有视觉吸引力。 Heres the example I was given. 这是我给的例子。 The white boxes were there because I was supposed to find the answers myself. 白盒子在那里,因为我应该自己找到答案。 So that can be ignored. 因此可以忽略。

正确的例子

And here's what mine looks like. 这就是我的模样。

我的例子

We haven't been taught anything other than printf so I don't know any alternatives. 除了printf,我们没有得到其他任何教育,所以我不知道有什么替代方法。

Here's my code. 这是我的代码。

long long lngFactoral = 1;
int intNumber = 1;

for (int intIndex = 1; intIndex <= 20; intIndex ++ )
{
    lngFactoral = lngFactoral * intIndex;
    printf("%d! = %lli ", intIndex, lngFactoral);

    intIndex++;

    lngFactoral = lngFactoral * intIndex;
    printf("                          %d! = %lli \n", intIndex, lngFactoral);
}

You can set field width in printf. 您可以在printf中设置字段宽度。 You will have to specify the width with the format specifier using the integer value that sets the field width. 您将必须使用设置字段宽度的整数值,使用格式说明符指定宽度。 For example, "%5d" or "%10d". 例如,“%5d”或“%10d”。

If the value to be printed is shorter than this number, the result is padded with blank spaces. 如果要打印的值小于此数字,则结果将用空格填充。

In your case your case you can modify your printf in the following manner: 在您的情况下,您可以按以下方式修改printf

First printf statement: 第一条printf语句:

 printf("%2d! = %20lli ", intIndex, lngFactoral);

Second printf statement: 第二个printf语句:

printf("   %2d! = %20lli \n", intIndex, lngFactoral);

%2d on the left-hand side is because you are finding the factorial of only 2 digit numbers, so we are going to set the field width 2. 左侧的%2d是因为您仅找到2位数字的阶乘,所以我们将设置字段宽度2。

Similarly, %20d is used on the right-hand side because the factorial of the largest number 20 is never going to exceed 20 digits. 同样,在右侧使用%20d ,因为最大数字20的阶乘永远不会超过20位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM