如何在C中打印此模式?

Mar*_*ist 1 c for-loop

我必须打印这个:

          0          
        1 0 1        
      2 1 0 1 2      
    3 2 1 0 1 2 3    
  4 3 2 1 0 1 2 3 4  
5 4 3 2 1 0 1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

我的代码:

#include<stdio.h>
    int main()
    {
        int i,j,k,l;

        for(i=1;i<=6;i++)
        {
            for(j=6;j>i;j--)
            {
                printf(" ");
            }

            for(k=i-1;k>=0;k--)
            {
                printf("%d",k);
            }

            for(l=1;l<i;l++)
                printf("%d",l);
            printf("\n");
        }
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我的输出:

     0          
    101        
   21012      
  3210123    
 432101234  
54321012345
Run Code Online (Sandbox Code Playgroud)

我刚刚开始用C编码,所以这对我来说是新的.如何在数字之间放置空格以使最终输出看起来比现在更优雅?

我试图%-6dprintf("%d",k);调整宽度,但它有输出错误的压痕.

pax*_*blo 5

这很容易解决.您当前打印一个字符(换行符除外)的任何地方,只需打印该字符后跟一个空格即可.

如果你这样做,你会看到你想要的输出:

          0 
        1 0 1 
      2 1 0 1 2 
    3 2 1 0 1 2 3 
  4 3 2 1 0 1 2 3 4 
5 4 3 2 1 0 1 2 3 4 5 
Run Code Online (Sandbox Code Playgroud)

我不会向你展示代码,因为它几乎可以肯定是课堂作业,如果你自己坚持下去,你会成为一个更好的编码器.但是我告诉你有三条线需要改变的小窍门.这应该是比足以让这个问题迎刃而解.

作为旁注,这将在最后一位数之后在每行的末尾打印一个空格.如果不允许这样做,有办法解决它,主要是通过更改最后一个循环,这样它就不会为行上的最终项目输出空间.

如果你开始尝试使用两位数的数字,它也将开始失败.要解决这个问题,您需要知道最宽的数字并使用printf带宽度的字段说明符.但是,由于它不符合原始规范,我没有实现(见YAGNI).


如果你想实现类似的东西(在行尾有较大的数字和删除的空格),你可以使用类似的东西:

#include<stdio.h>

#define COUNT 15

int main(void) {
    // Sanity check.

    if (COUNT < 1) return 0;

    // Get maximum width.

    int width = 1, value = COUNT;
    while (value > 9) {
        value /= 10;
        width++;
    }

    // For each line.

    for (int line = 1; line <= COUNT; line++) {
        // Output leading spaces.

        for (int column = COUNT; column > line; column--)
            printf("%*s ", width, "");

        // Output descending digits.

        for (int column = line - 1; column >= 0; column--)
            printf("%*d ", width, column);

        // Output ascending digits.

        for (int column = 1; column < line; column++) {
            printf("%*d", width, column);
            if (column < line - 1) putchar(' ');
        }

        // Finish off line.

        putchar('\n');
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它具有以下优点:

  • 它允许可变宽度.
  • 它使用更恰当的命名(和更少)循环变量.
  • 它不会输出每行末尾的空格.

如果这课堂作业,请不要使用它,你几乎肯定会被发现.