功能简单,效果出乎意料

时间:2017-04-17 15:06:35

标签: javascript function

所以我正在制作一个简单的程序来找到两个数字之间最大的公共分频器(lcd),使用欧几里得算法(http://www.math.jacobs-university.de/timorin/PM/continued_fractions.pdf,在第二页),这非常简单。所以这是我创建的功能:

        function largest_common_divider(num1, num2) {
            var remainder;
            var alpha = num1;
            var beta = num2;

            for (i = 0; i < 100; i++) { 
                /* we want to find an "n" such that
                   n * beta <= alpha < (n + 1) * beta 

                   I initiated n at 1 so that I could use n = 0 
                   as the end condition for my loop */        
                for (n = 1; n <= 0; n++) {
                    if (alpha > (n * beta)) {
                        //still didn't find the n
                    } else if (alpha == (n * beta)) {
                        //Hurray! our beta is the lcd
                        n = 0;
                        return beta;
                    } else {
                        // figure out the remainder
                        // and set n = 0 to terminate the loop
                        remainder = alpha - (n - 1) * beta;
                        n = 0;
                    }
                }
                //If we didn't find our lcd, than the previous beta
                //become the new alpha (largest number) and the
                //the remainder becomes the new beta (smaller number)
                alpha = beta;
                beta = remainder;
            }
        }

注意,在这个程序中我只期望正整数和num1&gt; numb2总是。

所以,为了测试这个功能我做了这个:

    var a = 45; var b = 15;

    var bloopidy = largest_common_divider(a,b);

    console.log("The largest common divider between " + a + " and " + b + " is: " + 
    bloopidy);

期望结果是15,但我得到的是“未定义”。我用了所有的小知识来调试这个,但我做不到!我需要帮助的人,任何人都表示赞赏。谢谢!!

1 个答案:

答案 0 :(得分:3)

你的第二个for循环永远不会运行:

for (n = 1; n <= 0; n++)

1不是<= 0,所以开始时条件不正确,所以循环永远不会开始。

这意味着您的代码可以缩减为:

    function largest_common_divider(num1, num2) {
        var remainder;
        var alpha = num1;
        var beta = num2;

        for (i = 0; i < 100; i++) { 
            alpha = beta;
            beta = remainder;
        }
    }

这不包含明确的return,因此会隐式返回undefined