如何使用 C# 列印一個二進位制三角形?


二進位制三角形由 0 和 1 構成。要建立一個這樣的三角形,你需要使用一個巢狀的 for 迴圈,並顯示 0 和 1,直到指定的行數。

for (int i = 1; i <= n; i++) {

   for (j = 1; j <= i; j++) {
      if (a == 1) {
         Console.Write("0");
         a = 0;
      } else if (a == 0) {
         Console.Write("1");
         a = 1;
      }
   } Console.Write("
"); }

在上面,“0”在 a 的值為 1 時顯示,而當 a 為 0 時,則顯示 1。透過這種方式,如果行數設定為 7,即 for 迴圈中 n 的值,那麼將會顯示以下二進位制三角形。

1
01
010
1010
10101
010101
0101010

示例

using System;
namespace Program {
   public class Demo {
      public static void Main(String[] args) {

         int j;
         int a = 0, n = 7;
         // looping from 1 to 7
         for (int i = 1; i <= n; i++) {
            for (j = 1; j <= i; j++) {
               if (a == 1) {
                  Console.Write("0");
                  a = 0;
               } else if (a == 0) {
                  Console.Write("1");
                  a = 1;
               }
            } Console.Write("
");          }          Console.ReadLine();       }    } }

更新於: 2020-06-22

422 次瀏覽

開啟您的 職業

完成課程獲取認證

立即開始
廣告
© . All rights reserved.