描述这个用于十进制到二进制转换的函数
Describe this function for Decimal to Binary conversion
我无法理解为什么它在Java和C++中打印总二进制位而不是最后一位。然而,在C++和java中,它打印所有的位。
public static void main(String[] args) {
toBin(2);
}// end of main
static void toBin(int b) {
int modu = 0;
if (b < 1) {
return;
}
modu = b % 2;
b=(b>>1);
toBin(b);
System.out.print(modu);
}// end of toBin()
这段代码在所有三种语言中都应该做同样的事情:它递归地打印数字的所有位。
让我们研究一下当你在5:上拨打toBin
时会发生什么
modu of the first level of invocation is set to 1 (5%2)
toBin is called on 2 (5>>1)
modu of the second level of invocation is set to 0 (4%2)
toBin is called on 1 (2>>1)
modu of the third level of invocation is set to 1 (1%2)
toBin is called on 0 (1>>1)
toBin returns because b < 1
modu of the third level is printed: 1; toBin returns
modu of the second level is printed: 0; toBin returns
modu of the first level is printed: 1; toBin returns
结果,打印了5的二进制表示101
。
toBin()的工作方式是,当除以两个时,它首先找到剩余部分
modu = b % 2;
将其添加到开头,然后除以2
b = b >> 1
并递归地重复,直到什么都没有了。
if (b < 1) {
return
}
如果你用十进制来思考,它会更容易一些。
假设你有4863这个数字,你想把它以10为基数打印出来。
首先你取n%10,它是3,然后你除以10,你得到486。重复,你有6和48,依此类推。
打印在toBin(b)之后的原因是它不需要维护字符串。相反,它将首先打印最内部的递归调用,当它退出时,它将反向打印其余的调用。
本质上,以下内容(可能更容易理解)也起到了同样的作用,但向后打印数字:
while (b >= 1) {
System.out.print(b % 2);
b /= 2;
}
您的程序(只需简单的移植工作)在C中也能很好地工作。。。你的问题是什么?
在对toBin
的每次调用中(除了最后一次),您都会打印一个数字,那么您希望得到什么呢?
如果只想打印最后一位,则不需要递归。仅System.out.print(b%2)
相关文章:
- C++从二进制转换为十进制数
- 我写的 ASCII 到二进制转换器C++向后显示二进制,如何使其正确显示?
- 十进制到二进制转换器 c++
- 将二进制转换为十进制,我如何要求用户仅输入二进制
- 十进制,包括负到 32 位二进制转换器
- 输入 1024 后十进制到二进制转换的输出错误?
- C 二进制转换为双精度的转换运算符
- 将二进制转换为负整数
- 如何将 32 位编译二进制转换为 64 位
- 如何在 C++ 中将二进制转换为十六进制
- 如何理解 c++ 中的 MNIST 二进制转换器?
- 以下对二进制转换代码的小数如何工作
- 具有递归功能的二进制转换给出一个奇数值
- 了解C++位操作中的二进制转换实现
- 编写将二进制转换为文本C 6的程序
- 反射格雷码到二进制转换中的幻数
- 为什么我总是必须除以 49 才能得到二进制转换器 + cout 歧义的正确答案?
- 如何使用库将二进制转换为十进制<bitset>?
- C++二进制转换为十进制,八进制
- 脚本到二进制转换和对象序列化