C#练习打印明星'*'

时间:2014-02-16 11:54:19

标签: c#

我正在练习在以下结果中生成星星。

*
**
***
**
*

代码:

private static void ShowStar(int p)
    {
        StringBuilder foward = new StringBuilder();
        StringBuilder reverse = new StringBuilder();

        for (int i = 0; i <= p; i++)
        {
            foward.Append('*');
            Console.WriteLine(foward.ToString());

            reverse.Insert(0,foward.ToString().Substring(1) + "\r\n");
            if (i == p) 
            {
                Console.WriteLine(reverse.ToString());
            }
        }

    }

但我想以更简单的方式打印它,有没有人有任何好主意?

非常感谢!!

4 个答案:

答案 0 :(得分:1)

    public static void ShowStar(int p)
    {
        for (int i = 1; i < p * 2; i++)
            Console.WriteLine(new string('*', (i < p) ? i : p * 2 - i));
    }

答案 1 :(得分:0)

将星形图案打印分成两个循环。

第一个循环打印

*
**

从行号1到行号(n / 2)

而第二个循环打印

*** 
**
*

这是来自行号(n / 2 + 1) to n。其中n是最大行号。 希望它能让你的代码更容易。

答案 2 :(得分:0)

只是为了好玩

string CreateArrow(int count)
{
    // Only one buffer
    StringBuilder sbAll = new StringBuilder();

    // The arrow needs an arrowhead
    if(count % 2 == 0) count++;

    // Create the arrowhead
    string s = new string('*', count);
    sbAll.AppendLine(s);

    // the rest of the arrow
    for(int x = count-1; x>0; x--)
    {
        s = new string('*', x);

        // before the arrowhead
        sbAll.Insert(0, s + Environment.NewLine);

        // after the arrowhead
        sbAll.AppendLine(s);

    }
    return sbAll.ToString();
}

答案 3 :(得分:0)

我建议先将这些行收集到一个数组中,然后打印出该数组。这种方式更清洁。想象一下,如果是后者,你想修改你的代码,并希望将它写入文件,或者用它进行其他处理。

    private static void ShowStar(int p)
    {
        // collecting data. In more complex environments this should be
        // in a separate method, like var lines = collectLines(p)
        var lines = new string[p*2+1];
        var stars = "*";
        for (int i = 0; i <= p; i++)
        {
            lines[i] = lines[p * 2 - i] = stars;
            stars += "*";
        }

        // writing the data. In more complex environments this should be
        // in a separate method, like WriteLines(lines)
        foreach (var line in lines)
        {
            Console.WriteLine(line);
        }
    }
相关问题