2013-10-05 60 views
0

首先我應該提到,我是C#的初學者。三種顏色重複

這是到目前爲止的代碼我做:

for (int row = 1; row <= 25; row++) 
     { 
      for (int col = 1; col <= 39; col++) 
      { 
       switch (row) 
       { 
        case 1: 
         Console.ForegroundColor = ConsoleColor.Yellow; 
         break; 
        case 2: 
         Console.ForegroundColor = ConsoleColor.Magenta; 
         break; 
        case 3: 
         Console.ForegroundColor = ConsoleColor.Green; 
         break; 

       } 
       Console.Write("* ");      
     } 
     Console.WriteLine(); 

我真的想了三種顏色:黃,品紅,青重複。

三個第一句是好的,但其餘的都是綠色的。

並且讓所有其他線路向右一步?

所有幫助表示讚賞

感謝

回答

3

在開關更改代碼:

for (int row = 1; row <= 25; row++) { 
       for (int col = 1; col <= 39; col++) 
       { 
        switch (row%3) 
        { 
         case 1: 
          Console.ForegroundColor = ConsoleColor.Yellow; 
          break; 
         case 2: 
          Console.ForegroundColor = ConsoleColor.Magenta; 
          break; 
         case 0: 
          Console.ForegroundColor = ConsoleColor.Green; 
          break; 

        } 
        Console.Write("* ");   
        } 
       Console.WriteLine(); 
+0

又見[%操作者(http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx)文檔 –

0
for (int row = 1; row <= 25; row++) { 
      for (int col = 1; col <= 39; col++) 
      { 
       int rowInd = row % 3; 
       switch (rowInd) 
       { 
        case 0: 
         Console.ForegroundColor = ConsoleColor.Yellow; 
         break; 
        case 1: 
         Console.ForegroundColor = ConsoleColor.Magenta; 
         break; 
        case 2: 
         Console.ForegroundColor = ConsoleColor.Green; 
         break; 

       } 
       Console.Write("* ");   
       } 
      Console.WriteLine(); 

給剛剛1,2,3行會賦值爲那些只。所以通過使用%符號,你會得到行/ 3的餘數。這是3/3,餘數= 0; 4/3,餘數= 1;和5/3;餘數= 2; 6/3再次爲0;

0

可以嘗試這樣的事:

 ConsoleColor[] colors = new ConsoleColor[] { 
     ConsoleColor.Yellow, 
     ConsoleColor.Magenta, 
     ConsoleColor.Green 
     }; 

     for (int row = 1; row <= 25; row++) 
     { 
      Console.ForegroundColor = colors[(row+1) % 3]; 
      for (int col = 1; col <= 39; col++) 
      { 
       Console.Write("*"); 
      } 
      Console.WriteLine(); 
     }