首页 > 解决方案 > 递归程序打印数字的问题

问题描述

我在下面的程序中有问题,下面的程序打印数字从 1 到 9,但我也想打印数字 10,我该怎么做?

function a(n){
    if(n == 1){
        return;
    }
    a(--n);
    console.log("hello world = ",n);    
}

a(10);

标签: javascriptrecursion

解决方案


只有当您的数字不为零时,您才需要切换退出条件并调用该函数。

function a(n) {
    if (n !== 1) a(n - 1);
    console.log("hello world =", n);
}

a(10);

你所拥有的是

function a(n){
    if (n == 1) {                     // exit condition
        return;                       // end of function run
    }
    a(--n);                           // mutating variable
    console.log("hello world = ", n);
}

检查值并结束函数的退出条件。这可以防止打印最后一个值。

另一个问题是n再次调用该函数的失败。后来使用的变量不再具有原始值。

通过将退出函数更改为检查是否应该再次调用该函数,与退出相反,它允许为每个想要的数字运行并进行输出。

如果您只是将 更改--nn - 1,则需要另一个输出1

function a(n){
    if (n == 1) {
        console.log("hello world = ", n); // add another output here for 1
        return;
    }
    a(n - 1);
    console.log("hello world = ", n);
}

a(10);


推荐阅读