日期:2014-05-20  浏览次数:20840 次

这道题 难住我了??
2/1 3/2 5/3 8/5 13/8 21/13……求前20项的和??

------解决方案--------------------
Java code


public class Test {

    public static void main(String[] args) {
        System.out.println(calc(20));
    }

    static double calc(int n) {
        int[] nums = new int[n + 1];
        nums[0] = 1;
        nums[1] = 2;
        for (int i = 2; i < n + 1; i++)
            nums[i] = nums[i - 2] + nums[i - 1];
        double sum = 0;
        for (int i = 0; i < n; i++) {
            sum += nums[i + 1] * 1.0 / nums[i];
        }
        return sum;
    }

}

------解决方案--------------------
上面我搞错了,弄成前5个了,应该是前20个数,源代码是这样的:
Java code
public class smp
{
    public static void main(String args[])
    {
        double a=1.0,b=2.0;
        double total=0;
        double [] c=new double [20]; 
        for(int i=0;i<20;i++)
        {
            c[i]=b/a;
            double temp;
            temp=b;
            b=a+b;
            a=temp;
            total+=c[i];
        }
        System.out.println("total="+total);
    }
}

------解决方案--------------------
Java code
public class Test003 {
    private static int count=0;
    private static double sum=0;
    public double sumAdd(int n){
        return this.sumAdd(2, 1, n);
    }
    public double sumAdd(double c,double bc,int n){
        if(n>=count){
            count++;
            sum+=c/bc;
            return sumAdd(c+bc,c,n);
        }else{
            return sum;
        }        
    }
    public static void main(String[] args){
        Test003 test=new Test003();
        System.out.println(test.sumAdd(20));
    }
}

------解决方案--------------------
Java code


public class HelloUbuntu {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HelloUbuntu test = new HelloUbuntu();
        System.out.println(""+test.sum(20));
        //32.66026079864164
    }
    double fun1(int i){
        if(i==1)return 2;
        if(i==2)return 3;
        return fun1(i-1)+fun1(i-2);
        }
    double fun2(int i){
        if(i==1)return 1;
        if(i==2)return 2;
        return fun2(i-1)+fun2(i-2);
        }
    double sum(int n){
        double sum=0.0;
        for(int i=1; i<=n;i++){
        sum+=fun1(i)/fun2(i);
        }
        return sum;
        }

}