gpt4 book ai didi

Java-Print 级数和级数之和

转载 作者:行者123 更新时间:2023-12-01 04:18:42 26 4
gpt4 key购买 nike

我正在编写一个程序来打印系列和系列的总和(接受用户的 X 和 N)。这是该系列:

S=1-X^2/2!+X^3/3!-X^4/4!....x^N/N!

这是我到目前为止所得到的:

import java.io.*;

public class Program6

{
int n,x;

double sum;
public void getValue() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input a value to be the maximum power");
n=Integer.parseInt(br.readLine());
System.out.println("input another value");
x=Integer.parseInt(br.readLine());
}
public void series()
{
sum=1.0;
double fact=1.0;
for(int a=2;a<=n;a++)
{
for(int b=a;b>0;b--)
{fact=fact*b;
}
double c=a/fact;
if(a%2==0)
sum=sum-(Math.pow(x,c));
else
sum=sum+(Math.pow(x,c));
fact=1;

}
}
public void display()
{
System.out.println("The sum of the series is " +sum);
}
public static void main(String args[])throws IOException
{
Program6 obj=new Program6();
obj.getValue();
obj.series();
obj.display();
}
}

我不知道如何打印该系列本身。

最佳答案

计算是以迭代方式完成的,这很好 - 但您不断运行计算出的值 sum而且你永远不会保存系列“项目” - 最好添加一个类(class)成员,也许像 List<Double> values并在每次计算新的系列项目时不断添加到其中,这样您就可以迭代列表并在计算完成后打印所有“成员”:

因此添加为类成员变量:

List<Double> values = new LinkedList<Double>();

现在您可以保存值:

public void series()
{
sum=1.0;
double fact=1.0;
for(int a=2;a<=n;a++)
{
for(int b=a;b>0;b--)
fact=fact*b;

double c=a/fact;
double newValue = Math.pow(x,c); // line changed

if(a%2==0)
newValue = -newValue; // sign calculation

values.add(newValue); // save the value
sum += newValue; // now add
fact=1;
}
}

//and it's also easy to display the values:
public void display()
{
System.out.println("The sum of the series is " +sum);
System.out.println("The members of the series are: ");
String str = "";
for(Double d : values){
str += d+", ";
}
str = str.substring(0,str.length()-2);//remove the last ","
System.out.println(str);
}

执行:

Input a value to be the maximum power
5
input another value
2
The sum of the series is 0.3210537507072142
The members of the series are:
-2.0, 1.4142135623730951, -1.122462048309373, 1.029302236643492

关于Java-Print 级数和级数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195566/

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