我如何格式化,以便在计算每小时里程后显示没有小数点?我根本不知道如何格式化。我目前得到的是它是四舍五入但它留下.0
之后它看起来不正确。我还必须将其保留为double
。
import java.util.Scanner;
import static java.lang.System.*;
import static java.lang.Math.*;
public class MilesPerHour {
private int distance, hours, minutes;
private double mph;
public MilesPerHour() {
setNums(0,0,0);
mph = 0;
}
public MilesPerHour(int dist, int hrs, int mins) {
distance = dist;
hours = hrs;
minutes = mins;
}
public void setNums(int dist, int hrs, int mins) {
}
public void calcMPH() {
mph = Math.round((distance)/(hours + (minutes/60)));
}
public void print() {
System.out.print(distance + " miles in " + hours + " hours and " + minutes + " minutes = " + mph + " MPH.");
}
public static void main( String[] args ) {
Scanner keyboard = new Scanner(in);
out.print("Enter the distance :: ");
int dist = keyboard.nextInt();
out.print("Enter the hours :: ");
int hrs = keyboard.nextInt();
out.print("Enter the minutes :: ");
int mins = keyboard.nextInt();
MilesPerHour test = new MilesPerHour(dist, hrs, mins);
test.calcMPH();
test.print();
}
}
答案 0 :(得分:2)
您可以使用String.format()
将双舍入显示为整数:
System.out.println("My number: " + String.format("%.0f", 2.5d));
将显示My number: 3
。
有关String格式化程序的语法,请参阅full documentation。
答案 1 :(得分:1)
从你的代码:
private double mph;
即使您为mph
分配了double
的返回值, Math.round()
仍会保留System.out.print()
。当您调用mph
时,double
被引用为System.out.print(" MPH: " + ((int)mph) );
,导致尾随" .0"。
只需添加如下所示的类型转换:
#include "