Enter a positive number x and a positive integer value of n, the following formula is required. Requires the definition of two function calls: fact (n) calculated n factorial; mypow (x, n) n-th power of x (i.e., xn), two types of function return value is double.
x - x2/2! + x3/3! + ... + (-1)n-1xn/n!
× outputs a 4 decimal places.
x n
Sequence sum
2.0 3
1.3333
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
double x = in.nextDouble();
int n = in.nextInt();
double y=0.0;
double sum=0.0;
for(int i=1;i<=n;i++){
y=Math.pow(-1, i-1)*mypow(x,i)/fact(i);
sum+=y;
}
System.out.printf("%.4f", sum);
}
public static double fact(int n){
double a=1;
for(int i=1;i<=n;i++){
a=a*i;
}
return a;
}
public static double mypow(double x, int n){
return Math.pow(x, n);
}
}