我无法理解为什么它打印总二进制位而不是 Java 和 C++ 中的最后一位。我在 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
作为结果,101
,即 5 的二进制表示,被打印出来。
关于java - 描述用于十进制到二进制转换的此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9010615/