如何使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP