系列中: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));
}
}
}
答案 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);
}
}