如何将最后一个术语作为Java中用户输入分母的系列进行求和

时间:2017-09-12 21:35:40

标签: java for-loop sum series

系列中:1/3 + 3/5 + 5/7 + 7/9 + 9/11 + .........#/ nth, 我试图使第n个系列的分母,例如如果用户输入5,它将计算1/3 + 3 / 5,5是用户输入的最后一个项。我能够使代码计算术语的数量,例如5将计算5个术语1/3 + 3/5 + 5/7 + 7/9 + 9/11。 这是我的代码:

import java.util.Scanner;
public class n01092281
{
//for loop that computes a sum of the series
    public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.println("Enter your nth term for the series.");
      double userInput = input.nextInt();   
      double sum = 0.0;
      for(int i = 2; i <= userInput*2; i+=2) {
        sum += ((double)(i-1)/(i+1));
       }
  }
}

1 个答案:

答案 0 :(得分:0)

问题在于你的for循环条件。您正在循环userInput*2次。按2减去它并将i初始化为1,因为您的序列以1作为分子开头。

import java.util.Scanner;

public class n01092281 {
    //for loop that computes a sum of the series
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter your nth term for the series.");
        double userInput = input.nextInt();
        double sum = 0.0;
        for (double i = 1; i <= userInput - 2; i += 2) {
            sum += (i / (i + 2));
        }
        System.out.println(sum);
    }
}