在C語言中,可以通過遞歸或迭代的方式編寫斐波那契數列。以下是兩種方法的示例代碼:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
return 0;
}
以上是兩種在C語言中編寫斐波那契數列的方法,您可以根據自己的需求選擇其中一種。