在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;
}