2014-01-16 79 views
0

我正在練習我的編程技巧,用一個相當常見的問題繪製一個由一個字母組成的ASCII樹(比如x)來繪製一棵樹。使用嵌套for循環繪製一棵ASCII樹

即:

Prompt: Enter the number of lines for your tree: 5 
Output: 
    x 
    xxx 
xxxxx 
xxxxxxx 
    x 

的解決方案,我有正在工作,我希望它。我只缺少一個特徵(這是我的問題的一部分)。 問題是,我不明白我用過的for-loop條件。是的,我確實從另一個人那裏得到了幫助,但我仍然不明白他們的邏輯,但它有效。請,請向我解釋for循環條件是如何爲我繪製我想要的。 x.x 此外,我無法繪製樹的最後一個「樹樁」,即最後一行的最後一個x。

這是我的代碼。

static void Main(string[] args) 
     { 
      int lines = 0; 
      Console.WriteLine("Enter number of lines: "); 
      string LinesAsString = Console.ReadLine(); 
      lines = Convert.ToInt32(LinesAsString); 
      print(lines); 
     } 


     public static void print(int lines) 
     { 

      for (int i = 0; i < lines; i++) 
      { 
       for (int a = 0; a < lines-i-1; a++) 
       { 
        Console.Write(" "); 
       } 

       for (int y = 0; y < i*2 + 1; y++) 
       { 

        Console.Write("x"); 


       } 
       Console.WriteLine(); 

      } 





     } 

任何幫助表示讚賞。

謝謝。

回答

0

第一for循環打印左填充(所有空格)。表達式lines - i - 1來自於需要居中樹的事實,並且您知道線0具有單個x,行1具有3(xxx),行2具有5(xxxxx)等等。但左空格的數量取決於樹的總行數,因此您需要考慮lines以及當前行的索引(它是變量的值i)。爲了弄清楚這兩者之間的關係,你可以只用少量的水平的嘗試,讓我們說3:

__x  2 for the 1st line. 
_xxx 1 for the 2nd line. 
xxxxx 0 for the 3rd line. 

第二for環打印x秒。它知道對於第一行(i = 0)它需要打印單個x,所以當i0,y需要是1,因此+ 1* 2來自進展i * 2 + 1 = {1, 3, 5, 7...},這是每行中的x s的數量。

要打印最後一個存根字符,可以使用與第一個for循環中相同的邏輯,插入第一行的空格數量,然後插入一個空格,然後單擊一個x

Console.Write(new String(' ', lines - 1) + "x"); 

這應該只是for循環包含其他兩個循環後加入。

+0

愚蠢的問題 - 當你指的是'當前行的索引'時,我代表什麼? – TimelordViktorious

+0

我的意思是變量'i',它表示在包含另外兩個''for''的每個迭代中哪一行正在輸出到輸出中。剛編輯答案澄清這一點。 –

+0

謝謝 - 這是非常有幫助的。我現在好像明白了。我唯一擔心的是,將來會出現類似的問題,我可能需要幫助解決這類問題!這種問題解決策略的任何提示? :p – TimelordViktorious

0

這很簡單:

的第一個for循環的每次迭代繪製一條線。假設你有4行(我不考慮所述一個與孤獨X):

線1(I = 0):3個空格1×
線2(I = 1):2位3×
線3(I = 2):1個空間5×
線4(I = 3):0空格7×

從這些,則可以得到的空格數,X的,行索引之間的關係我和行數。

spaces = (lines - i) - 1 // decreases by one every iteration starting at lines - 1 
    x = i * 2 + 1 // the odd numbers in increasing order 

第一回路繪製空間和第二個中的X的

0
int count = 0; 
      for (int i = 0; i < 8; i++) 
      { 
       for (int x = 0; x < 8-i-1; x++) 
       { 
        Console.Write(" "); 
       } 
       for (int j = 0; j < i*2+1; j++) 
       { 
        Console.Write("X"); 
       } 
       Console.WriteLine(); 
      } 
      //solution to your stump problem 
      for (int i = 0; i < 4; i++)//the no. 4 means that you stump will be made from four X's 
      { 
       for (int x = 0; x < 8-count-1; x++) 
       { 
        Console.Write(" "); 

       } 
       Console.Write("X"); 
       Console.WriteLine(); 
      } 
      Console.ReadKey();