下面是一個用C語言編寫斐波那契數(shù)列的示例代碼:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main() {
int n, i;
printf("Enter the number of terms in the Fibonacci sequence: ");
scanf("%d", &n);
printf("Fibonacci sequence: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
這段代碼首先定義了一個遞歸函數(shù)fibonacci
,用于計算第n個斐波那契數(shù)。然后在main
函數(shù)中,用戶輸入要輸出的斐波那契數(shù)列的項數(shù),然后循環(huán)調用fibonacci
函數(shù)輸出相應的斐波那契數(shù)。運行該代碼將輸出指定項數(shù)的斐波那契數(shù)列。