C语言实验——分数序列

来源:互联网 发布:新技术新工艺软件下载 编辑:程序博客网 时间:2024/06/05 22:42

Problem Description
有一个分数序列:2/1, 3/2, 5/3, 8/5, 13/8, …编写程序求出这个序列的前n项之和。
Input
输入只有一个正整数n,1≤n≤10。
Output
输出该序列前n项和,结果保留小数后6位。
Example Input
3
Example Output
5.166667

#include <iostream>#include <stdio.h>#include <math.h>using namespace std;int main(){    int n;    double sum, p;    int a, b;    a=2;    b=1;    sum=a*1.0/b;    cin>>n;    for(int i=2;i<=n;i++)    {        p=a;        a=a+b;        b=p;        sum+=a*1.0/b;    }    printf("%.6lf\n",sum);    return 0;}
原创粉丝点击