/* * 斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987......这个数列从第3项开始,每一项都等于前两项之和。 */ #includeint main() { //输出指定数量的斐波那契数列 int i, n, t1 = 0, t2 = 1, nextTerm; printf("输出几项: "); scanf("%d", &n); printf("斐波那契数列: "); for (i = 1; i <= n; ++i) { printf("%d, ", t1); nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; } printf("\n"); // 输出指定数字前的斐波那契数列 t1 = 0, t2 = 1; printf("输入一个正数: "); scanf("%d", &n); // 显示前两项 printf("斐波那契数列: %d, %d, ", t1, t2); nextTerm = t1 + t2; while(nextTerm <= n) { printf("%d, ",nextTerm); t1 = t2; t2 = nextTerm; nextTerm = t1 + t2; } printf("\n"); return 0; }
输出: