C语言有一分数序列:2/13/25/38/513/821/13....求出这个数列的前N项之和,保留两位小数
时间: 2023-09-28 19:12:53 浏览: 102
#include <stdio.h>
int main() {
int n, i;
double sum = 0, a = 2, b = 13, c;
scanf("%d", &n); // 输入要求和的前n项
sum = a + b; // 前两项和
for (i = 3; i <= n; i++) { // 从第三项开始循环
c = b + a + i - 1; // 根据规律计算第i项
sum += c; // 累加前i项和
a = b; // 更新前两项
b = c;
}
printf("%.2f\n", sum); // 输出答案(保留两位小数)
return 0;
}
相关问题
C语言有一分数序列: 2/1 3/2 5/3 8/5 13/8 21/13...... 求出这个数列的前N项之和,保留两位小数。
C语言求分数序列前N项之和的代码如下:
```c
#include <stdio.h>
float fractionSum(int n) {
float sum = 0;
float numerator = 2, denominator = 1;
float temp;
for (int i = 0; i < n; i++) {
sum += numerator / denominator;
temp = numerator;
numerator = numerator + denominator;
denominator = temp;
}
return sum;
}
int main() {
int N = 20;
float sum = fractionSum(N);
printf("The sum of the first %d terms in the fraction sequence is %.2f\n", N, sum);
return 0;
}
```
运行结果:
```
The sum of the first 20 terms in the fraction sequence is 32.66
```
c语言有一分数序列:1/2,2/3,3/5,5/8,8/13,13/21...求出这个数列的前20项之和。
代码如下:
```c
#include <stdio.h>
int main() {
double a = 1, b = 2, sum = 0;
for (int i = 1; i <= 20; i++) {
sum += b / a;
double temp = a + b;
a = b;
b = temp;
}
printf("前20项之和为:%lf", sum);
return 0;
}
```
输出结果为:前20项之和为:32.660260。
阅读全文