代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var num = parseInt(window.prompt('input'));
var first = 1;
var second = 1;
var third;
if(num > 2){
for(var i = 0; i < num-2; i++){
third = first + second;
first = second;
second = third;
}
document.write(third);
}
else{
document.write(1);
}
</script>
</body>
</html>
输出结果第 4 项为 3,第 5 项为 4.调试后发现 first 的结果总是 1,真是搞不懂,请大神帮忙看看!
1
yngby 2019-04-23 09:23:24 +08:00
为啥我试了一下没错呢
|
2
mango88 2019-04-23 09:24:54 +08:00 via iPhone
第一项难道不是 1 ?
|
3
wangsongyan 2019-04-23 09:26:07 +08:00
我这对的
|
4
vexjoe 2019-04-23 09:30:03 +08:00
|
5
wenzichel 2019-04-23 09:36:58 +08:00
没错的呀!
```javascript function fb(num) { var first = 1; var second = 1; var third; if(num > 2){ for(var i = 0; i < num-2; i++){ third = first + second; first = second; second = third; } return third; } else{ return first; } } for(let i=1; i<10; i++) { console.log(i, fb(i)); } /* 1 1 2 1 3 2 4 3 5 5 6 8 7 13 8 21 9 34 */ ``` |
6
wenzichel 2019-04-23 09:37:48 +08:00
不支持 markdown 啊,那我怎么删除我上面的这条评论呢
|
7
DJQTDJ 2019-04-23 10:09:54 +08:00
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> var increment = 0; while(increment < 100) { var first = 1; var second = 1; var third; if(increment > 2){ for(var i = 0; i < increment-2; i++){ third = first + second; first = second; second = third; } document.write(increment + ":" + third + "<br>"); } else{ document.write(increment + ":" + 1 + "<br>"); } increment++; } </script> </body> </html> 没问题吖 |
8
Jase 2019-04-23 10:18:34 +08:00
function fibonacci(n) {
if (n === 1) { return 1; } if (n === 2) { return 1; } return fibonacci(n - 1) + fibonacci(n - 2); } |
10
Paperex OP 各位大哥,是我之前把 for 循环里的“ first ”写成了“ first ”。可这帖子没法删除……。感谢各位大神!
|
11
dartabe 2019-04-23 11:22:40 +08:00
各位大神 插一个问题 之前网上说这个数列求法最好不用递归 对 JS 是不是也成立呢?
|
13
airdge 2019-04-23 11:50:40 +08:00
function F(n) {
if (n == 1) { return 1 } else if (n == 2) { return 1 } else { return F(n - 1) + F(n - 2) } } console.log(F(9)) |
15
stevenbipt 2019-04-23 11:55:05 +08:00 via Android
递归写法是个狼人~
|
16
silentstorm 2019-04-23 12:47:21 +08:00
通项公式:(Math.pow((1+Math.sqrt(5))/2,n)-Math.pow((1-Math.sqrt(5))/2,n))/Math.sqrt(5)
就是会有精度损失 |
17
bzw875 2019-04-23 13:10:16 +08:00
function fibonacci(n) {
if (n < 2) { return 1; } var arr = [1,1]; for (i = 1; i < n; i++) { arr[i + 1] = arr[i - 1] + arr[i]; } return arr[n]; } console.log(fibonacci(10)); 你们要么函数栈太深,要么重复计算每个值,应该用一个数组保持每一项的值。这样比较快 |