【问题标题】:How could I align my output to the center?我怎样才能将我的输出对齐到中心?
【发布时间】:2021-09-16 23:29:42
【问题描述】:
    #include<stdio.h>
    int main()
    {
        int n ;
        printf("Input the number of rows: ");
        scanf("%d", &n);

        for(int i = 1; i <= n ; i++)
        {
            for(int j = 1 ; j <= i ; j++)
            {
                if(j == i + 1)
                {
                    break;
                }

                printf("%3d", j);
    
            }
            for(int  j = i - 1 ; j > 0; j--)
            {
                if(j == 0)
                {
                    break;
                }
                printf("%3d", j);
            }
            printf("\n");
            
        }
    }

节目环节

Number of rows for this output n = 3

My output:   
            1
            1  2  1      
            1  2  3  2  1


Preferred output:   
                  1
               1  2  1      
            1  2  3  2  1
           

这是一个练习,我必须打印一个数字金字塔,其中金字塔的中心数字是行数。我理解其中的逻辑,但如您所见,我未能成功完成任务。有什么建议吗?

【问题讨论】:

  • 通过添加另一个循环来打印必要的空格?
  • 任何具体且解释清楚的想法将不胜感激
  • 您可以从n 总数或行数和i 当前行数和3 硬编码到printf("%3d", j); 中计算所需的空格数。最后一行可以作为printf("%*d", width, j); 完成,其中width 是计算可以使用的变量或常数。或者,在循环中使用printf("%3c", ' ');
  • 我不太明白。你能提供一个示例代码吗?
  • 请尝试计算一下。在纸上尝试,首先写下每行开头所需的空格数,然后弄清楚如何计算该数字。给你一些代码来复制/粘贴不会真正帮助你。

标签: c for-loop indexing output alignment


【解决方案1】:

正如@WeatherWane 所指出的,您需要添加逻辑来添加额外的空格。如果你仔细注意到,每行上的空格数(不包括用%3d 添加的填充等于3 * (n - i))。你可以创建一个像这样的简单方法来添加空格:

void addSpaces(int N, int currentIndex, int padding) {
  for (int index = currentIndex; index < N; index++)
      for (int spaces = 0; spaces < padding; spaces++)
         printf(" ");
}

然后你可以像这样从你的第一个 for 循环中调用它:

  for(int i = 1; i <= n ; i++)
    {
      addSpaces(n, i, 3);
      for(int j = 1 ; j <= i ; j++)
        {
           // ...

我测试了它,它似乎正确对齐:

c-posts : $ ./a.out 
Input the number of rows: 5
              1
           1  2  1
        1  2  3  2  1
     1  2  3  4  3  2  1
  1  2  3  4  5  4  3  2  1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2014-08-22
    • 1970-01-01
    • 2013-12-26
    • 2022-08-11
    • 1970-01-01
    • 2011-11-24
    相关资源
    最近更新 更多