如何在C#中打印以下模式?

时间:2015-07-30 11:34:09

标签: c# text console

如何将以下样式的文本打印到C#控制台应用程序?

1111111
 22222
  333
   4

提前致谢。

1 个答案:

答案 0 :(得分:1)

直立三角形:

static void Main(string[] args) {
    const int height = 4;
    for(int row = 0; row < height; row++) {
        //left padding
        for(int col = 0; col < height - row - 1; col++) {
            Console.Write(' ');
        }
        //digits
        for(int col = 0; col < row * 2 + 1; col++) {
            Console.Write((char)('1' + row));
        }
        //right padding (is this needed?)
        for(int col = 0; col < height - row - 1; col++) {
            Console.Write(' ');
        }
        Console.WriteLine();
    }
    Console.ReadKey();
}

打印:

   1   
  222  
 33333 
4444444

颠倒三角形:

static void Main(string[] args) {
    const int height = 4;
    for(int row = 0; row < height; row++) {
        //left padding
        for(int col = 0; col < row; col++) {
            Console.Write(' ');
        }
        //digits
        for(int col = 0; col < (height - row) * 2 - 1; col++) {
            Console.Write((char)('1' + row));
        }
        //right padding (is this needed?)
        for(int col = 0; col < row; col++) {
            Console.Write(' ');
        }
        Console.WriteLine();
    }
    Console.ReadKey();
}

打印:

1111111
 22222 
  333  
   4   
相关问题