C#圣诞树

时间:2015-09-29 11:14:58

标签: c# algorithm

我是C#的新手,因为我请求帮助我实现这个:

        *
        *
       ***
        *
       ***
      *****
        *
       ***
      *****
     ******* 
        *
       ***
      *****
     ******* 
    ********* 

我刚才有这段代码:

class Program
{
    static void Main(string[] args)
    {
        AnotherTriangle ob = new AnotherTriangle();
        ob.CreateTriangle();

        Console.ReadLine();
    }
}
class AnotherTriangle
{
    int n;
    string result = "*";
    public void CreateTriangle()
    {
    flag1:
        Console.Write("Please enter number of triangles of your tree: ");
        n = int.Parse(Console.ReadLine());
        Console.WriteLine();
        if (n <= 0)
        {
            Console.WriteLine("Wrong data type\n"); goto flag1;
        }
        string s = "*".PadLeft(n);
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine(s);
            s = s.Substring(1) + "**";
            for (int j = 0; j < n; j++)
            {
                Console.WriteLine(s);
            }
        }
    }
}

现在我只有&#34;塔&#34;,而不是等边三角形。请帮忙。

1 个答案:

答案 0 :(得分:10)

Console.WriteLine("Please enter the number of triangles in your tree: ");
int n = int.Parse(Console.ReadLine());

for (int i = 1; i <= n; i++)
{
    for (int j = 0; j < i; j++)
    {
        string branch = new String('*', j);
        Console.WriteLine(branch.PadLeft(n + 3) + "*" + branch);
    }
}

A working example.