js 求前n项的 fibnaci 数列和

 1     function f(n) {
 2         var num1 = 1,
 3             num2 = 1;
 4         if (n == 1)
 5             document.write(num1);//n=1,输出1
 6         else if (n > 1) {
 7             document.write(num1 + " " + num2 + " ");//n>=2;先输出前2项
 8             for (var i = 3; i < n; i++) {
 9                 var result = num1 + num2;
10                 document.write(result + " ");
11                 num1 = num2;
12                 num2 = result;
13             }
14         }
15 
16     }
17     f(3);

 

posted @ 2016-10-05 16:16  游离的心  阅读(588)  评论(0编辑  收藏  举报