【问题标题】:C# christmas treeC# 圣诞树
【发布时间】:2015-09-29 20:00:11
【问题描述】:

我是 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);
            }
        }
    }
}

现在我只有“塔”,没有等边三角形。请帮忙。

【问题讨论】:

  • 拜托,当你得到它的工作时,看看使用TryParse并质疑你为什么使用goto
  • goto?真的吗?感谢您是新手,但请不要再使用goto。它会引导你走上“糟糕的开发者”的道路,这可能是一条难以逃脱的道路。
  • 了解gotogoto-is-this-bad
  • 永远不要使用 goto - 直到你知道为什么不这样做;) - 在一些罕见的情况下它可能有用。

标签: c# algorithm


【解决方案1】:
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.

【讨论】:

  • 12 分钟内的精彩答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2014-01-13
  • 2021-12-22
  • 1970-01-01
  • 2015-08-23
相关资源
最近更新 更多