在javascript中的阶乘。不行

时间:2012-06-05 18:19:34

标签: javascript math factorial

这是脚本,我不明白为什么它不起作用...

function FirstFactorial(num) {

var lower = num - 1;
var qq = 0;

while (num > 0) {
var qq === num * lower;
num--;
lower--;
}
num === qq;
return num;
}
FirstFactorial(num);

2 个答案:

答案 0 :(得分:7)

=是赋值运算符,===是严格相等运算符

答案 1 :(得分:4)

此功能存在很多问题,请参阅注释。

function FirstFactorial(num) {
    var lower = num - 1;
    var qq = 0;

    while (num > 0) {
        // here you are shadowing the "qq" variable in the outer scope
        // delete the "var" keyword to fix this
        // also === is an identity operator, i think you wanted assignment (=)
        // so this line becomes: qq = num * lower;
        var qq === num * lower;
        num--;
        lower--;
    }

    // assuming that === was supposed to be = again
    // you can rewrite this as just: return qq;
    num === qq;
    return num;
}

FirstFactorial(num);

即使使用这些语法修复,您计算阶乘的逻辑也不正确。

编辑:工作示例(因为我很无聊)http://jsfiddle.net/gU2cz/