2015-09-28 87 views
-1

我需要將二進制數字邏輯添加到此代碼段中。我只是不能換我周圍的頭如何實現二進制數,我可以只添加0 S和1秒,但似乎並沒有被正確如何在C中打印二進制數字的三角形#

namespace Star_Pyramid 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     int num; 
     Console.WriteLine("enter level"); 
     num = Int32.Parse(Console.ReadLine()); 
     int count = 1; 

     for (int lines = num; lines >= 1; lines--) 
     { 

      for (int spaces = lines - 1; spaces >= 1; spaces--) 
      { 
       Console.Write(" "); 

      } 
      for (int star = 1; star <= count; star++) 
      { 
       Console.Write("*"); 
       Console.Write(" "); 

      } 
      count++; 

      Console.WriteLine(); 
     } 
     Console.ReadLine(); 
    } 
    } 
} 
+0

請解釋你的意思是「添加二進制數邏輯」 –

+0

@SamiKuhmonen我需要打印由二進制數組成的三角形 –

+0

@MohammadQasim第一個內部'for'可以替換爲'Console.Write(new String ('',lines - 1));' –

回答

2

可以使用modulo%

c = star % 2;  // will print first the '1' 
    c = (star + 1) % 2; // will print first the '0' 

int num; 
    Console.WriteLine("enter level"); 
    num = Int32.Parse(Console.ReadLine()); 
    int count = 1; 
    int c = 0; 

    for (int lines = num; lines >= 1; lines--) 
    { 

     for (int spaces = lines - 1; spaces >= 1; spaces--) 
     { 
      Console.Write(" "); 

     } 
     for (int star = 1; star <= count; star++) 
     { 
      c = star % 2; //this will return 1 if the value of star is odd then 0 if even 
      Console.Write(c); 
      Console.Write(" "); 

     } 
     count++; 

     Console.WriteLine(); 
    } 
    Console.ReadLine(); 

VIEW DEMO

+0

就是上面提到的線,什麼是0:1;意思? –

+0

交替打印1和0 ..試試看演示 –

+0

哦,我明白了。所以0:1;有點像Console.Write(「0」)和Console.Write(「1」); ? –