JavaScript, Golang, Python和PHP实现的都写过了,今天用C再来一下
什么是斐波那契
斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........
这个数列从第3项开始,每一项都等于前两项之和
代码实现
#include <stdio.h>
int a = 0;
int b = 0;
int tmp;
int fibonacci() {
if (a == 0) {
a = 1;
} else {
tmp = a;
a = a + b;
b = tmp;
}
return a;
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d ", fibonacci());
}
return 0;
}
Output:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55