js 求前n项的 fibnaci 数列和

时间:2024-01-07 20:56:32
     function f(n) {
var num1 = 1,
num2 = 1;
if (n == 1)
document.write(num1);//n=1,输出1
else if (n > 1) {
document.write(num1 + " " + num2 + " ");//n>=2;先输出前2项
for (var i = 3; i < n; i++) {
var result = num1 + num2;
document.write(result + " ");
num1 = num2;
num2 = result;
}
} }
f(3);