1

シリーズとシリーズの合計を出力するプログラムを作成しています(ユーザーから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();
    }
}

シリーズ自体を印刷する方法がわかりません。

4

1 に答える 1

0

計算は反復的な方法で行われますが、これは良いことですが、計算された値を実行し続けsum、シリーズの「アイテム」を保存することはありません-クラスメンバーを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
于 2013-10-05T08:40:38.567 に答える