在C语言中,可以使用递归或循环两种方法实现斐波那契数列。
#include <stdio.h>
int fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main() {
int n;
printf("请输入要计算的斐波那契数列项数:");
scanf("%d", &n);
printf("斐波那契数列的第%d项是:%d\n", n, fibonacci(n));
return 0;
}
#include <stdio.h>
int fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
} else {
int a = 0, b = 1, i, fib;
for (i = 2; i <= n; i++) {
fib = a + b;
a = b;
b = fib;
}
return b;
}
}
int main() {
int n;
printf("请输入要计算的斐波那契数列项数:");
scanf("%d", &n);
printf("斐波那契数列的第%d项是:%d\n", n, fibonacci(n));
return 0;
}