0

我的目标是使用递归来使 sigma 表示法工作。上限为 n(输入变量) 下限为 i=1,函数为 (-i)^(i-1)。我让它与迭代一起工作,但我无法让递归工作。

<!DOCTYPE html>
<head><title>Recursion</title></head>
<body>
<h1>Recursion</h1>
<script = "text/javascript">
var num
var i;
var n;
var total;
total = 0;
i=0;
var b;
b=0;
function formula(n)
{
(Math.pow((-i),(i-1)))
}

function recursion(n)
{
i=i+1;
if ((n-i) == 0)
{
document.writeln("done");
}
else
{
total = total + recursion(formula(n-i));
return total;

//total = total + (Math.pow((-i),(i-1)) + recursion(n-i));
}
}
num = window.prompt("pick a number");
recursion(num);
document.writeln(recursion(num));
//document.writeln(total);

</script>
</body>
</html>
4

1 回答 1

2

Please avoid any global variables, that makes it very hard to read. Also, indent your code properly; and don't mix the output (document.write) into the computation. If you don't understand the recursion, just use a loop:

var total = 0;
for (var i=1; i<=n; i++)
    total += formula(i);
return total; // the result

The same thing, done with recursion:

function sumFormulaUpTo (n) {
    if (n <= 0) // the abort condition
        return 0;
    else
        return sumFormulaUpTo(n-1) + formula(n);
}
sumFormulaUpTo(100);

You notice: there is no total variable, only the result of the recursively called function is used.

With an end recursion (more like the loop), it would look like this:

function sumFormulaFromTo(total, i, n) {
    if ( i > n )
        return total;
    else {
        var newtotal = total + formula(i);
        return sumFormulaFromTo(newtotal, i+1, n);
    }
}
sumFormulaFromTo(0, 1, 100);

If you had total and n declared statically outside the function, it would look more like yours. Yet, you forgot to return the result once the end condition is met (you just output something, but return undefined), and you somehow called the recursion with the result of formula - no idea where you got that from. This causes an infinite loop, according to @cbayram.

于 2012-10-21T21:35:07.850 回答