【发布时间】:2019-10-14 21:17:45
【问题描述】:
这是我程序中双“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.
【问题讨论】:
标签: java math decimal rounding