描述这个用于十进制到二进制转换的函数

Describe this function for Decimal to Binary conversion

本文关键字:二进制 转换 函数 十进制 用于 描述      更新时间:2023-10-16

我无法理解为什么它在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)