将斐波那契数列前20项写入文件fab.txt中,并将斐波那契数列前20项之和输出到屏幕上,要求斐波那契数列第n项的计算用递归函数实现。
#include <stdio.h> // 递归函数来计算斐波那契数列的第n项 int fibonacci(int n) { if (n <= 1) return n; return (fibonacci(n - 1) + fibonacci(n - 2)); } int main() { FILE *file = fopen("fab.txt", "w"); if (file == NULL) { printf("cannot open this file"); return 1; } int n = 20; int sum = 0; printf("前20项斐波那契数列:\n"); fprintf(file, "前20项斐波那契数列:\n"); for (int i = 0; i < n; i++) { int fib = fibonacci(i); printf("%d ", fib); fprintf(file, "%d ", fib); sum += fib; } printf("\n前20项斐波那契数列之和:%d\n", sum); fprintf(file, "\n前20项斐波那契数列之和:%d\n", sum); fclose(file); return 0; }
标签:20,数列,将斐波,int,斐波,那契 From: https://www.cnblogs.com/daiang/p/17710040.html