js用递归实现斐波那契数列

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>

window.onload = function () {
var number1 = document.getElementById("number1");//获取元素
var number2 = document.getElementById("number2");

function fn(a) {//定义函数 用递归
if (a <= 2) {//临界值设置
return 1;
} else {

return fn(a - 1) + fn(a - 2);//调用自身
}


}
btn.onclick = function () {//点击事件

var num1 = number1.value;//获取元素
//console.log(num1);
var m = fn(num1);
//console.log(m);
number2.value = m;//写入文本框

}

}

</script>
</head>

<body>
请输入数字:
<input type="text" id="number1">
<input type="button" value="生成" id="btn">
<br> 斐波那契数:
<input type="text" id="number2">
</body>

</html>
posted @ 2019-04-01 11:58  sun丶凹凸曼  阅读(2162)  评论(0编辑  收藏  举报