【问题标题】:positioning a pair of chars(*) center instead of left [duplicate]定位一对字符(*)中心而不是左侧[重复]
【发布时间】:2019-01-29 17:05:36
【问题描述】:

所以我正在努力使用控制台应用程序。需要字符线形成树状图案而不是右翼三角形。像这样(3):

  *
 ***
*****

到目前为止我有这个:

int rows = int.Parse(Console.ReadLine());

for(int i = 1; i <= rows; i++)
 {
            for(int x = 1; x <= i; x++)
            {
                Console.Write("*");
            }
            Console.WriteLine("\n");
 }

【问题讨论】:

    标签: c# for-loop char


    【解决方案1】:

    我认为您正在寻找 PadLeft 函数。它会在左侧的字符串中添加空格,以便您可以正确定位它。此外,您需要将行数乘以 2 并将步长增加 1。您将获得以下代码:

    int rows = int.Parse(Console.ReadLine()) * 2;
    
    for (int i = 1; i <= rows; i += 2) {
      Console.Write( "".PadLeft( (rows - i) / 2) );
      for(int x = 1; x <= i; x++) {
        Console.Write("*");
      }
      Console.WriteLine();
    }
    

    另外,如果你真的想让你的三角形看起来像这样,你可能需要删除这行:

    Console.WriteLine("\n");
    

    ...并将其更改为:

    Console.WriteLine();
    

    (这将删除不必要的换行符,WriteLine 已经打印了换行符)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2023-03-08
      • 2023-03-04
      相关资源
      最近更新 更多