gpt4 book ai didi

java - 缩短极大数字的可能方法?

转载 作者:行者123 更新时间:2023-11-30 06:40:22 26 4
gpt4 key购买 nike

这是我程序中双“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com