I'm need to create Java program to find sum of series S = 1 + 1!/x + 2!/x2 + … + N!/xN.
My code is working correctly for the sum but they want my result output to be with five decimals (result - 2.75 to be 2.75000). I'm using DecimalFormat for results who are more than five decimals and it work. But how to print results with two decimals - with five?
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculate {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.#####");
Scanner scanner = new Scanner(System.in);
double n = scanner.nextDouble();
double x = scanner.nextDouble();
double factorial = 1;
double pow = 1;
double S = 0;
double result;
for (int i = 1; i <= n; i++) {
factorial *= i;
pow *= x;
result = (factorial / pow);
S += result;
}
double finalResult = (S + 1);
String formatted = df.format(finalResult);
System.out.println(formatted);
}
}