帮我写个求斐波那契数列第n项的函数,用c语言
时间: 2024-12-13 11:24:56 浏览: 1
计算fibonacci数的前个数-c语言程序设计 数组与结构 ppt
在C语言中,你可以通过递归或迭代的方式来编写求解斐波那契数列的函数。这里提供一个简单的迭代方法,因为它通常比递归更高效。以下是递归和迭代版本的代码示例:
**递归版本(效率较低,不适合大n值)**:
```c
#include <stdio.h>
int fibonacci_recursive(int n) {
if (n <= 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
int main() {
int n;
printf("Enter the index of Fibonacci number: ");
scanf("%d", &n);
printf("Fibonacci number at position %d is: %d\n", n, fibonacci_recursive(n));
return 0;
}
```
**迭代版本(效率较高)**:
```c
#include <stdio.h>
int fibonacci_iterative(int n) {
if (n <= 0)
return 0;
else if (n == 1)
return 1;
int fib = 0, prev_fib = 1, current_fib = 1;
for (int i = 2; i < n; i++) {
fib = prev_fib + current_fib;
prev_fib = current_fib;
current_fib = fib;
}
return fib;
}
int main() {
int n;
printf("Enter the index of Fibonacci number: ");
scanf("%d", &n);
printf("Fibonacci number at position %d is: %d\n", n, fibonacci_iterative(n));
return 0;
}
```
阅读全文