2013-09-24 55 views
1

我開始學習C#,並且遇到了一個我的任務中的問題。這項任務是創建一個由星星組成的金字塔。高度由用戶輸入指定。For循環跳到最後

由於某種原因,我的第一個for循環跳到最後。在調試時,我注意到變量height收到bar的值,但在此之後它跳到最後。我不知道爲什麼,因爲代碼對我來說似乎很好。

do - while如果輸入的值爲0或更低,那麼循環會詢問用戶是否有新值。

using System; 

namespace Viope 
{ 
    class Vioppe 
    { 
     static void Main() 
     { 
      int bar; 

      do 
      { 
       Console.Write("Anna korkeus: "); 
       string foo = Console.ReadLine(); 
       bar = int.Parse(foo); 
      } 
      while (bar <= 0); 

      for (int height = bar; height == 0; height--) 
      { 
       for (int spaces = height; spaces == height - 1; spaces--) 
       { 
        Console.Write(" "); 
       } 
       for (int stars = 1; stars >= height; stars = stars * 2 - 1) 
       { 
        Console.Write("*"); 
       } 
       Console.WriteLine(); 
      } 
     } 
    } 
} 
+3

你想'高度> = 0'。你的'for'循環甚至不會啓動,因爲條件是錯誤的。 – Jonesopolis

回答

6

for循環的條件是它必須保持是真正爲了進入狀態循環體。所以這樣的:

for (int height = bar; height == 0; height--) 

應該是:

for (int height = bar; height >= 0; height--) 

否則,執行任務,那麼它會檢查height是否爲0,如果不是(這勢必會是這種情況),這是循環的結束。

有關更多信息,請參閱MSDN documentation for for loops

3

試試這個: -

for (int height = bar; height >= 0; height--) 

代替

for (int height = bar; height == 0; height--) 
2

只有當bar小於或等於零時纔會退出while循環。所以最初在for循環的height = bar(它大於0)。你檢查高度是否等於零,這是錯誤的。要檢查> = 0

0
for (int height = bar; height == 0; height--) 

您的條件:height == 0;永遠是真實的。

爲了它是真實的,高度必須0
並且爲了高度爲0,酒吧必須0

如果bar0,比你甚至不會已經得到了你的for循環,因爲這個無限while循環的:

while (bar <= 0);