c语言中生成fibonacci数列中的第n项
时间: 2024-12-13 13:25:15 浏览: 60
在C语言中,生成Fibonacci数列中的第n项可以使用循环或递归的方式来实现。这里我会给你展示两种方法:
1. **循环法**:
```c
#include <stdio.h>
long long fibonacci(int n) {
if (n <= 0) return 0;
else if (n == 1) return 1;
long long fib = 1, prev_fib = 1;
for (int i = 2; i < n; i++) {
long long temp = fib;
fib += prev_fib;
prev_fib = temp;
}
return fib;
}
int main() {
int n;
printf("Enter the position of the Fibonacci number: ");
scanf("%d", &n);
printf("The %dth Fibonacci number is: %lld\n", n, fibonacci(n));
return 0;
}
```
2. **递归法**(虽然效率较低,但为了演示递归思想):
```c
#include <stdio.h>
long long fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
// 使用递归时需要注意性能,因为有大量重复计算
int main() {
int n;
printf("Enter the position of the Fibonacci number: ");
scanf("%d", &n);
printf("The %dth Fibonacci number is: %lld\n", n, fibonacci(n));
return 0;
}
```
阅读全文
相关推荐


















