如何使用 C# 中的遞迴將數字從十進位制轉換為二進位制?


若要獲得十進位制的二進位制,首先使用遞迴設定十進位制數 −

int dec = 30;

現在將值傳遞給函式 −

public int displayBinary(int dec) {
}

現在,檢查條件,直到十進位制值變為 0,然後使用遞迴獲取十進位制 num 的模 2,如下所示。遞迴呼叫將再次呼叫具有 dec/2 值的函式 −

public int displayBinary(int dec) {
   int res;
   if (dec != 0) {
      res = (dec % 2) + 10 * displayBinary(dec / 2);
      Console.Write(res);
      return 0;
   } else {
      return 0;
   }
}

以下為完整程式碼 −

示例

線上演示

using System;

public class Program {
   public static void Main(string[] args) {
      int dec;
      Demo d = new Demo();
      dec = 30;
      Console.Write("Decimal = "+dec);
      Console.Write("
Binary of {0} = ", dec);       d.displayBinary (dec);       Console.ReadLine();       Console.Write("
");    } } public class Demo {    public int displayBinary(int dec){       int res;       if (dec != 0) {          res = (dec % 2) + 10 * displayBinary(dec / 2);          Console.Write(res);          return 0;       } else {          return 0;       }    } }

輸出

Decimal = 30
Binary of 30 = 11110

更新日期:2020 年 6 月 22 日

393 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.