Возможный способ сократить очень большие числа? - PullRequest
2 голосов
/ 15 октября 2019

Это значение двойного «м» в моей программе (масса планеты после вычислений, это значение специально для массы Земли)

  • 5.973405437304745E24

При печати с использованием System.out.println (м);Вывод:

  • 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.

1 Ответ

4 голосов
/ 15 октября 2019

Вы можете использовать следующий код:

double x = 5.973405437304745e24;
System.out.printf("Mass: %.2e kg.%n", x);

, который выводит Mass: 5.97e+24 kg..

%.2e форматирует число, а %n просто добавляет символ новой строки. .2 указывает на то, что после точки желательны два десятичных знака. e запрашивает научную запись от форматера.

Проблема с Math.round() заключается в том, что результат сохраняется в long, который не может представлять такое большое число.

...