簡體   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