要获取Decimal的二进制文件,请使用递归,首先设置十进制数-
int dec = 30;
现在将值传递给函数-
public int displayBinary(int dec) { }
现在,检查条件,直到十进制值为0,然后使用递归获取十进制num的mod 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("\nBinary of {0} = ", dec); d.displayBinary (dec); Console.ReadLine(); Console.Write("\n"); } } 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