繁体   English   中英

我对“将十进制转换为二进制字符串”代码中的递归感到困惑

[英]I'm confused by recursion in my “convert decimal to binary string” code

void print_binary(int number)
{
    if (number){
        print_binary(number/2);
        putc((number % 2) ? '1' : '0', stdout);
    }
}
int main(void) {
    print_binary(8);
}

上面的代码返回“1000”。 但是当我将print_binary()中的两行反转并这样写时:

void print_binary(int number)
{
    if (number){
        putc((number % 2) ? '1' : '0', stdout);
        print_binary(number/2);
    }
}

字符串是“0001”。

我不明白为什么会这样。 任何解释表示赞赏。 谢谢

在第一个代码示例中,执行如下:

print_binary(8/2)
    print_binary(4/2)
        print_binary(2/2)
            print_binary(1/2)    // 1/2 = 0 => this is terminating condition of recursion
                                 // stack windup from here
            putc((1 % 2) ? '1' : '0', stdout);   --> output 1
        putc((2 % 2) ? '1' : '0', stdout);  --> output 0
    putc((4 % 2) ? '1' : '0', stdout);   --> output 0
putc((8 % 2) ? '1' : '0', stdout);    --> output 0

因此, output 是1000

在第二个代码示例中,执行如下:

putc((8 % 2) ? '1' : '0', stdout);    --> output 0
print_binary(8/2)

    putc((4 % 2) ? '1' : '0', stdout);   --> output 0
    print_binary(4/2)

        putc((2 % 2) ? '1' : '0', stdout);  --> output 0
        print_binary(2/2)

            putc((1 % 2) ? '1' : '0', stdout);   --> output 1
            print_binary(1/2)    // 1/2 = 0 => this is terminating condition of recursion
                                 // stack windup from here and nothing to do after last 
                                 // recursive call

因此, output 是0001

当您调用 function 时,程序将当前地址放入堆栈 memory 堆栈指针指向的位置,以便在执行结束时返回并跳转到函数的地址。 堆栈是一种 LIFO(后进先出)结构,因此当您调用 function 时,程序会完成 function 中的指令,而不是返回原来的位置。 这就是为什么要更改订单。

void print_binary(int number)
{
    if (number){
        putc((number % 2) ? '1' : '0', stdout);  // 1st instruction
        print_binary(number/2); // 2nd instruction
    }
}

该程序的工作原理如下:

  1. 8%2 是 0 所以打印 0。 // 第一个实例的第一条指令
  2. 出现了新的function。 跳转到它并将当前地址压入堆栈。 //第一个实例的第二条指令
  3. 4%2 是 0 所以打印 0。 //第二个实例的第一条指令
  4. 出现了新的 function。 跳转到它并将当前地址压入堆栈。 //第二个实例的第二条指令
  5. 2%2 是 0 所以打印 0 // 第三个实例的第一条指令
  6. 出现了新的function。 跳转到它并将当前地址压入堆栈。 //第三个实例的第二条指令
  7. 1%2 为 0 所以打印 1 //第 4 个实例的第 1 条指令
  8. ...

所以 output 是 0001

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM