Latest web development tutorials

C 練習實例24

C 語言經典100例 C語言經典100例

題目:有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數列的前20項之和。

程序分析:請抓住分子與分母的變化規律。

程序源代碼:

//  Created by www.w3big.com on 15/11/9.
//  Copyright © 2015年 本教程. All rights reserved.
//

#include <stdio.h>

int main()
{
    int i,t;
    float sum=0;
    float a=2,b=1;
    for(i=1;i<=20;i++)
    {
        sum=sum+a/b;
        t=a;
        a=a+b;
        b=t;
    }
    printf("%9.6f\n",sum);  
}

以上實例輸出結果為:

32.660263

C 語言經典100例 C語言經典100例