c - 如何将循环输出中的字符居中?

标签 c formatting

我希望打印帕斯卡三角形的图案,但在这里遇到了困难。还没有找到解决方案,因为我找到的大多数解决方案仅解释如何打印图案(没有适本地格式化输出,即只是一个三角形而不是金字塔形状)。

int pascal(int length)
{
    int row=1,col;
    while(row<=length)
    {
        col=0;
        while(col<row)
        {
             printf(" ");
             printf("*");
             col++;
        }
        printf("\n");
        row++;
    }
}

int main()
{
    int x;
    printf("How many rows in the triangle? ");
    /* Rows = Columns. This is just the size of the triangle. */
    scanf("%d",&x),
    pascal(x);
    return(0);
} 

这是当前输出

How many rows in the triangle?
*
* *
* * *
* * * *

...这就是我正在寻找的

   *
  * *
 * * *
* * * *

最佳答案

#include <stdio.h>
#define MAX 1000
int main()
{
    int row,mid,tab,temp,num;
    printf("Enter no of Rows: ");
    scanf("%d",&row);

    tab=row-1;

    int arr1[MAX],arr2[MAX];

    for (int i=1;i<=row;i++,tab--)
    {
        printf("\t\t\t\t");
        temp=tab;

        arr1[0]=1; arr1[i-1]=1;

        for(;temp>=1;temp--)
            printf("  ");

        if (i==1)
            printf("1  ");

        else
        {
            arr2[0]=1; arr2[i]=1;
            int l=0,m=1;
            for (int j=1;j<i;j++)
            {

                arr2[j]=arr1[l]+arr1[m];
                l++,m++;
            }

            for(int j=0;j<i;j++)
                {
                    if(j==0)
                        printf("%d  ",arr1[j]);
                    else
                        printf(" %d  ",arr1[j]);
                }
            for (int j=0;j<=i;j++)
                arr1[j]=arr2[j];
        }
        printf("\n");

    }

    return 0;
}

Go through this carefully. Comment if you have problems understanding it.

关于c - 如何将循环输出中的字符居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50820034/

相关文章:

php - 从 MySql 数据库中提取文本并将其拆分为网站上的段落

asp.net - 将 Gridview 导出到 Excel,并将行格式化为文本

c - 宏中 "do {...} while (0)"和 "{...} ((void)0)"之间的实际区别?

c - 文件是如何保存的?

C 程序对输入值进行向下舍入

android - 在 Android 的 textview [ Html.fromhtml() ] 中使用多种文本颜色

c++ - 正确格式化有错误的数字 (C++)

c - printf ("%d %d %d\n",++a,a++,a) 输出

计算字符数组中的个数

c++ - boost 区域设置格式百分比