2014-02-16 108 views
-2

我正在練習以下結果中生成星。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()); 
      } 
     } 

    } 

但我想更簡單的方法來打印,沒有任何人有任何好的想法?

非常感謝!

+5

http://codereview.stackexchange.com –

回答

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); 
     } 
    } 
+0

它真的有幫助,謝謝〜 – andy

+0

任何時候,隊友^。^ – Hegi

0

將星型圖案打印成兩個循環。

首先環路打印

* 
** 

即從行號1到行數(n/2)

而第二個循環打印

*** 
** 
* 

這是行號(n/2 + 1) to n。其中n是最大行數。 希望它能讓你的代碼更容易。

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(); 
} 
+0

它是真正有用的,謝謝〜 – andy

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)); 
    } 
+0

這太酷了,太謝謝你許多!! – andy