题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前 20 项之和。
程序分析:请抓住分子与分母的变化规律。
import java.util.Scanner;
public class WangDao {
public static void main(String[] args){
System.out.print("Input the number of items: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("The answer is " + func(n));
}
public static double func(int n) {
double x = 2, y = 1, sum = 0;
double item, temp;
for (int i = 0; i < n; i++) {
item = x / y;
sum += item;
temp = x; // 用temp暂存一下x非常重要。
x = x + y;
y = temp; // 因为新一轮的y是旧一轮的x,然而x已经更新,所以用temp。
}
return sum;
}
}