#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//斐波那契数列,输入M求哪一项最接近这个M,输出其和f[i]
//斐波那契数列数列 1 1 2 3 5 8 13.....后面都是前两项的和
//找到最接近M的索引
int findFi(int M) {
int f1 = 1, f2 = 1, x = 2;
int i = 3;
if (M == 1) {
return 1;
}
while (x <= M) {
if (x == M) {
return i;
}
f1 = f2;
f2 = x;
x = f1 + f2;
i++;
}
i = (abs(x - M) < abs(M - f2)) ? i : (i - 1) ;
return i;
}
//求和
int sumfibonacci(int x) {
int x1 = 1, x2 = 1, x3 = 2;
int sum = 2; //前2项和为4
if (x == 1) {
printf("第%d项和为1\n", x);
} else if (x == 2) {
printf("第%d项和为2\n", x);
}
for (int i = 3; i <= x; i++) {
sum += x3;
x1 = x2;
x2 = x3;
x3 = x1 + x2;
}
printf("前%d项和为%d\n", x, sum);
}
int main() {
int M;
printf("请输入一个M:\n");
scanf("%d", &M);
int i = findFi(M);
printf("第%d项最接近%d\n", i, M);
printf("\n");
sumfibonacci(i);
}
斐波那契数列,输入M求哪一项最接近这个M,输出其和f[i]
最新推荐文章于 2024-10-30 16:47:45 发布