java源码:
package studying; import java.util.Scanner; public class Sum_Of_FirstN { /* * Topic: There is a score sequence: 2/1, 3/2, 5/3, 8/5, 13/8, 21 13 ... * find the sum of the first 20 of this series. */ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Please enter n :"); int n = input.nextInt(); double a = 2; double b = 1; double sum = 0; double t; for(int i = 1; i <= n; i++) { sum += a/b; //this is key point. t = a; a = a + b; b = t; } System.out.println("The sum of the first n of the sequence:\n" + sum); } }
结果展示:
时间: 2024-11-09 03:19:13