带五位小数的双精度格式
Format double with five decimals
我需要创建 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);
}
}
只需使用这种格式:
DecimalFormat df = new DecimalFormat("0.00000");
我需要创建 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);
}
}
只需使用这种格式:
DecimalFormat df = new DecimalFormat("0.00000");