gpt4 book ai didi

java - 如何计算Java中第n项是用户输入的系列的总和

转载 作者:行者123 更新时间:2023-12-02 12:15:59 25 4
gpt4 key购买 nike

我正在尝试计算总和和 Pi。我已经可以进行 Pi 计算,但在求和方面遇到困难。求和的输出应该计算 1/3 + 3/5 + 5/7 .... a number/n 第 n 项是用户输入,但我不确定我的计算。如果我输入 5,输出应该计算 1/3 + 3/5,但是这段代码会添加 5 项 1/3 + 3/5 + 5/7 + 7/9 + 9/11,我做错了什么?这是代码:

import java.util.Scanner;
public class n01092281
{
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));
}
System.out.printf("The sum of the series is %12.12f" , sum);
double Pi = 0;
for (int counter = 1; counter < userInput; counter++){
Pi += 4 * (Math.pow(-1,counter + 1)/((2*counter) - 1));
}
System.out.printf(" ,The computation of Pi is %1.12f", Pi);
}
}

最佳答案

我想,你的计算是正确的。我只是改变了你使用 i 的方式。此外,您只需要更新您想要去的具体次数即可。

这就是我改变的方式

      double userInput = 11;
int count =0;
if(userInput>=3){
count =(int)( userInput-1)/2;
}
double sum = 0.0;
for(int i = 1; i <= count; i++) {
sum += ((double)(2*i-1)/(2*i+1));
System.out.print((2*i-1)+"/"+(2*i+1)+' ');
}
System.out.println();
System.out.printf("The sum of the series is %12.12f" , sum);

输出:-

1/3 3/5 5/7 7/9 9/11 
The sum of the series is 3.243578643579

这里我也打印一个系列,给大家说清楚。

关于java - 如何计算Java中第n项是用户输入的系列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com