描述此十进制到二进制转换函数 我不能理解为什么它打印爪哇和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() publicstaticvoidmain(字符串[]args){ 托宾(2); }//干管末端 静态空隙托宾(int b){ int modu=0; if(b>1); 托宾(b); 系统输出打印(modu); }//托宾结束()
您的程序(通过简单的移植工作)在C语言中也可以正常工作。。。你的问题是什么?在每次给托宾打电话时(除了最后一个),你都会打印一个数字,那么你期待什么呢 如果只想打印最后一位,则不需要递归。只需描述此十进制到二进制转换函数 我不能理解为什么它打印爪哇和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() publicstaticvoidmain(字符串[]args){ 托宾(2); }//干管末端 静态空隙托宾(int b){ int modu=0; if(b>1); 托宾(b); 系统输出打印(modu); }//托宾结束(),java,c++,c,Java,C++,C,您的程序(通过简单的移植工作)在C语言中也可以正常工作。。。你的问题是什么?在每次给托宾打电话时(除了最后一个),你都会打印一个数字,那么你期待什么呢 如果只想打印最后一位,则不需要递归。只需System.out.print(b%2)toBin()的工作方式是,它首先在除以2时找到剩余的内容 modu = b % 2; 将其添加到开头,然后除以2 b = b >> 1 然后递归地重复,直到什么都没有了 if (b < 1) { return } 这段代码在所有三种语言
System.out.print(b%2)
toBin()的工作方式是,它首先在除以2时找到剩余的内容
modu = b % 2;
将其添加到开头,然后除以2
b = b >> 1
然后递归地重复,直到什么都没有了
if (b < 1) {
return
}
这段代码在所有三种语言中都应该做同样的事情:它递归地打印数字的所有位 让我们研究一下当您拨打电话5时发生的情况:
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
第一级调用的modu设置为1(5%2)
托宾在2号被召唤(5>>1)
第二级调用的modu设置为0(4%2)
托宾在1号被召唤(2>>1)
第三级调用的modu设置为1(1%2)
托宾在0上被调用(1>>1)
托宾回来是因为b<1
打印第三级modu:1;托宾回归
打印第二级modu:0;托宾回归
打印第一级modu:1;托宾回归
结果,
101
,5的二进制表示形式被打印出来。问题是什么?这是Java,而不是C或C++,你可以吸引那些不特别喜欢java的java用户;你确定它只打印C中的最后一位吗?在所有三种语言中,它都应该做同样的事情。如果我用java或C++打印2的二进制,它就显示了完整的二进制10。但在c语言中它只打印1,为什么?。我想你现在可能明白了
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