如何在C#中使用递归将数字从十进制转换为二进制?
要获取Decimal的二进制文件,请使用递归,首先设置十进制数-
int dec = 30;
现在将值传递给函数-
public int displayBinary(int dec) {
}现在,检查条件,直到十进制值为0,然后使用递归获取十进制num的mod2,如下所示。递归调用将再次使用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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短