这是我程序中双“m”的值(计算后的行星质量,这个值是专门针对地球质量的)
- 5.973405437304745E24
使用 System.out.println(m) 打印时; 输出为
- 5.973405437304745E24(正确输出)
使用 System.out.println(Math.round(m)) 打印时; 输出为
- 9223372036854775807(输出不正确)
我怎样才能缩短 m 的值以使其在 %6s 之内? 例如像这样
- 5.97E24
这是我下面的代码。该作业要求我们以格式化图表输出最终值(正如我在下面尝试做的那样)
//Java imports
import java.util.*;
import java.lang.Math;
//Main class
class Main {
public static void main(String[] args) {
//Initializing scanner name userInput
Scanner userInput = new Scanner (System.in);
//Greeting statement, prompts user to input the circumference in km
System.out.println("\nWelcome to the Escape Velocity Application. To begin, please enter the following information below. \nEnter the circumference (km):");
//Stores circumference in double named "circum" and converts the value to its meter equivalent (unit conversion required)
double circum = userInput.nextDouble() * Math.pow(10, 3);
//Prompts user to input the acceleration in m/s^2
System.out.println("Enter the acceleration due to gravity (m/s^2):");
//Stored value in double named "f"
double f = userInput.nextDouble();
//Gravitational Constant
double G = 6.67408e-11;
//1 - Radius calculation using the circumference of a circle formula
double r = circum/(2*Math.PI);
//2 - Mass calculation using the gravity formula
double m = f*Math.pow(r, 2)/G;
//3 - Calculation escape velocity using the escape velocity formula
double e = (Math.sqrt((2.0*G*(m))/r));
//Final output statements
System.out.println("\nThe radius is: " + Math.round(r * Math.pow(10, -3)) + " kilometers.");
System.out.println("The mass is: " + m + " kg.");
System.out.println("The escape velocity is: " + Math.round(e) + " m/s.");
//Formatted output statements
System.out.format("\n%20s %6s %10s", "Radius:", Math.round(r * Math.pow(10, -3)), "km.");
System.out.format("\n%20s %6s %10s", "Mass:", Math.round(m), "kg.");
System.out.format("\n%20s %6s %10s", "Escape Velocity:", Math.round(e), "m/s.");
}
}
这就是输出的样子。由于m值太长,第二行的中心发生了偏移。
The radius is: 6378 kilometers.
The mass is: 5.973405437304745E24 kg.
The escape velocity is: 11181 m/s.
Radius: 6378 km.
Mass: 9223372036854775807 kg.
Escape Velocity: 11181 m/s.
最佳答案
您可以使用以下代码:
double x = 5.973405437304745e24;
System.out.printf("Mass: %.2e kg.%n", x);
输出质量:5.97e+24 kg。
。
%.2e
格式化数字,%n
仅添加换行符。 .2
指定点后需要两位小数。 e
向格式化程序请求科学计数法。
Math.round() 的问题是,结果存储在无法表示如此大数字的 long
中。
关于java - 可能的方法来缩短非常大的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58384183/