编写一个斐波那契数列
时间: 2023-11-20 11:59:31 浏览: 47
以下是两种Python编写斐波那契数列的例子:
1.输出斐波那契数列前10个数
```python
a, b = 0, 1
for i in range(10):
print(a, end=' ')
a, b = b, a+b
# 输出:0 1 1 2 3 5 8 13 21 34
```
2.输出斐波那契数列小于1000的所有数
```python
a, b = 0, 1
while b < 1000:
print(b, end=' ')
a, b = b, a+b
# 输出:1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
```
相关问题
c语言编写一个斐波那契数列
好的,以下是 C 语言编写斐波那契数列的代码:
```c
#include <stdio.h>
int main() {
int n, i;
int fib[100] = {0, 1}; // 初始化前两个数
printf("请输入要输出的斐波那契数列项数:");
scanf("%d", &n);
for (i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2]; // 计算第 i 个数
}
printf("斐波那契数列前 %d 项为:\n", n);
for (i = 0; i < n; i++) {
printf("%d ", fib[i]); // 输出前 n 项
}
return 0;
}
```
用c语言编写一个斐波那契数列
以下是用C语言编写斐波那契数列的两种方法:
方法一:递归法
```c
#include <stdio.h>
int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
int main() {
int n = 10;
for (int i = 1; i <= n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
```
方法二:循环法
```c
#include <stdio.h>
int main() {
int n = 10;
int a = 1, b = 1, c;
printf("%d %d ", a, b);
for (int i = 3; i <= n; i++) {
c = a + b;
printf("%d ", c);
a = b;
b = c;
}
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)