Java计算为int的双打印

  • 本文关键字:打印 int 计算 Java java
  • 更新时间 :
  • 英文 :


让用户输入int,计算为double,打印为int。我做了这个,但它会打印成int。我该怎么修?

System.out.println("Please input integer a: ");
double a = input.nextDouble();
System.out.println("Please input integer b: ");
double b = input.nextDouble();
System.out.println("Please input integer c: ");
double c = input.nextDouble();
System.out.println("Please input integer d: ");
double d = input.nextDouble();

double result = a / b + c / d;

System.out.println("Input a: " + a);
System.out.println("Input b: " + b);
System.out.println("Input c: " + c);
System.out.println("Input d: " + d);

System.out.println(" " + a + " " + c);
System.out.println("--- + --- = " + result);
System.out.println(" " + b + " " + d);

使用Scanner.nextInt并将int转换为仅用于result计算的double:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please input integer a: ");
int a = input.nextInt();
System.out.print("Please input integer b: ");
int b = input.nextInt();
System.out.print("Please input integer c: ");
int c = input.nextInt();
System.out.print("Please input integer d: ");
int d = input.nextInt();
double result = (double) a / (double) b + (double) c / (double) d;
System.out.println("Input a: " + a);
System.out.println("Input b: " + b);
System.out.println("Input c: " + c);
System.out.println("Input d: " + d);
int fractionBarABLength = Math.max(String.valueOf(a).length(), String.valueOf(b).length());
String fractionBarAB = "-".repeat(fractionBarABLength);
int fractionBarCDLength = Math.max(String.valueOf(c).length(), String.valueOf(d).length());
String fractionBarCD = "-".repeat(fractionBarCDLength);
String paddedA = String.format("%1$" + fractionBarABLength + "s", a);
String paddedB = String.format("%1$" + fractionBarABLength + "s", b);
String paddedC = String.format("%1$" + fractionBarCDLength + "s", c);
String paddedD = String.format("%1$" + fractionBarCDLength + "s", d);
System.out.printf("%s   %s%n", paddedA, paddedC);
System.out.printf("%s + %s = %.2f%n", fractionBarAB, fractionBarCD, result);
System.out.printf("%s   %s%n", paddedB, paddedD);
}
}

示例用法:

Please input integer a: -1
Please input integer b: 2
Please input integer c: 3
Please input integer d: 4
Input a: -1
Input b: 2
Input c: 3
Input d: 4
-1   3
-- + - = 0.25
2   4

最新更新