如何将金字塔保存为字符数组?

时间:2019-04-07 11:02:07

标签: c# arrays if-statement

我需要检查 IF 的帮助,数组中的位置必须保存''或'*',以便以后在程序中打印出金字塔。

static void Main(string[] args)
    {
        Console.WriteLine("Enter size: ");
        int s = int.Parse(Console.ReadLine());

        char[,] pyramid = new char[s, s * 2 - 1];

        FillArray(pyramid);
        Out(pyramid);

        Console.ReadLine();
    }

    static void FillArray(char[,] t)
    {   
        for (int i = 0; i < t.GetLength(0); i++)
        {
            for (int j = 0; j < t.GetLength(1); j++)
            {
                if (j == t.GetLength(1) / 2 || j == t.GetLength(1) / 2 + i || j == t.GetLength(1) / 2 - i)
                {
                    t[i, j] = '*';
                }
                else t[i, j] = ' ';
            }
        }
    }

    static void Out(char[,] t)
    {
        for (int i = 0; i < t.GetLength(0); i++)
        {
            for (int j = 0; j < t.GetLength(1); j++)
            {
                Console.Write(t[i, j]);
            }
            Console.WriteLine();
        }
    }

此刻我出来像这样的东西:

console output

1 个答案:

答案 0 :(得分:1)

代码应该像这样

int i, j, n;

Console.WriteLine("Enter size: ");
n = int.Parse(Console.ReadLine());

for (i = 0; i < n; i++)
{
    for (j = 1; j <= n - i; j++)
        Console.Write(" ");
    for (j = 1; j <= 2 * i - 1; j++)
        Console.Write("*");
    Console.Write("\n");
}