7-34 求分数序列前N项和 (15 分)

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_43526304/article/details/85237641

本题要求编写程序,计算序列 2/1+3/2+5/3+8/5+... 的前N项之和。注意该序列从第2项起,每一项的分子是前一项分子与分母的和,分母是前一项的分子。

输入格式:

输入在一行中给出一个正整数N。

输出格式:

在一行中输出部分和的值,精确到小数点后两位。题目保证计算结果不超过双精度范围。

输入样例:

20

输出样例:

32.66

思路:使用中间变量存储分母

#include <stdio.h>
int main() 
{
    int n;
    scanf("%d",&n);
    double x = 2.0;
    double y = 1.0;
    double d;
    int c;
    double s= 0.0;
    double t;
    for(c = 1;c<n+1;c++)
    {
        d = x/y;
        s += d;
        t = x;
        x += y;
        y = t;
    }
    printf("%.2f\n",s);
return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43526304/article/details/85237641