求n以内的斐波那契数列
时间: 2024-01-16 07:16:50 浏览: 68
以下是两种求n以内斐波那契数列的方法:
1.使用JavaScript代码实现:
```javascript
var n = parseInt(window.prompt('输入你要求的斐波那契数列的位数'));
var first = 1, second = 1, third;
if (n > 2) {
for (var i = 0; i < n - 2; i++) {
third = first + second;
first = second;
second = third;
}
console.log("斐波那契数列前" + n + "项为:" + "1 1 " + (second - first));
} else if (n == 1 || n == 2) {
console.log("斐波那契数列前" + n + "项为:1");
} else {
console.log("输入有误!");
}
```
2.使用Python代码实现:
```python
a, b = 1, 1
n = int(input("请输入一个正整数:"))
if n <= 0:
print("输入有误!")
elif n == 1:
print("斐波那契数列前%d项为:" % n, a)
else:
print("斐波那契数列前%d项为:" % n, end=" ")
print(a, b, end=" ")
for i in range(2, n):
c = a + b
a = b
b = c
print(b, end=" ")
```
阅读全文