在此示例中,您將學(xué)習(xí)顯示前n個(gè)數(shù)字的斐波那契數(shù)列(由用戶輸入)。
要理解此示例,您應(yīng)該了解以下C語言編程主題:
斐波那契數(shù)列是下一個(gè)項(xiàng)是前兩個(gè)項(xiàng)之和的序列。 斐波那契數(shù)列的前兩個(gè)項(xiàng)是0,然后是1。
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
#include <stdio.h>
int main() {
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("斐波納契數(shù)列: ");
for (i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}輸出結(jié)果
Enter the number of terms: 10 斐波納契數(shù)列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
#include <stdio.h>
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
//顯示前兩個(gè)項(xiàng),始終為0和1
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while (nextTerm <= n) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}輸出結(jié)果
Enter a positive integer: 100 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,