我需要創建 Java 程序來找到 S = 1 + 1!/x + 2!/x2 + … + N!/xN 序列的總和。我的代碼對于總和工作正常,但他們希望我的結果輸出為五位小數(結果 - 2.75 為 2.75000)。我正在將DecimalFormat用于超過五位小數的結果并且它有效。但是如何打印兩位小數的結果 - 五位?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); }}
添加回答
舉報
0/150
提交
取消