我在试着计算一个求和和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);
}
}发布于 2017-09-13 02:28:05
我想,你的计算是正确的。我只是改变了你使用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这里我也是打印系列,给你讲清楚。
发布于 2017-09-13 13:31:02
根据你的问题,你的级数是r/n,其中n是第n项。使用这个简单的函数将数列求和到第n项。
private static void sum_up_series(int nth) {
double sum = 0;
for (int i = 0; i < nth; i++) {
int r = (1 + (i * 2));
int n = (3 + (i * 2));
if (n <= nth) {
sum += (double) (r) / (n);
System.out.print(r + "/" + n + " ");
}
}
System.out.print("\nsum = " + sum);
}以下是n= 11的输出
1/3 3/5 5/7 7/9 9/11 sum = 3.2435786435786436https://stackoverflow.com/questions/46183011
复制相似问题