我目前的代码有问题。我必须将小时和分钟声明为 int,将 totalTimeHours 声明为 double。totalTimeHours 用于以小时为单位存储总时间,例如 6.555 小时。例如,我正在处理的问题需要在几小时和几分钟内找到答案。6小时36分钟。对于我的最后一次跑步,我需要使用 14.7 加仑的汽油和 359.5 的距离。我使用 hours = (int)totalTimeHours 来提取整数 6,并且应该找到剩余的时间并将其乘以 60 以找到分钟,但这就是我被耽搁的地方。
下面是我的代码:
public static void computeMilesPerGallon()
{ //start brackett for computeMilesPerGallon
double gallons, distance, mpg, totalTimeHours; //totalTimeHours is the total time in just hours
//for example totalTimeHours = 6.5555 hrs
int minutes, hours;
final String DASHES = "-----------------------------------------------";
final double AVERAGE_SPEED = 54.5;
DecimalFormat oneDecimalDigits = new DecimalFormat ("0.0"); //prints decimal to 1 places
DecimalFormat threeDecimalDigits = new DecimalFormat ("0.000"); //prints decimal to 3 places
System.out.println ("\n\t\t\tSpeed Problem");
System.out.println ("\t\t\t-------------");
System.out.print ("\n\t\tEnter in the gallons of gas used: "); //gets gallons of gas used
gallons = scan.nextDouble();
System.out.print ("\t\tEnter in the total distance driven: "); //gets total distance driven
distance = scan.nextDouble();
mpg = distance / gallons; //calculates mpg
System.out.println ("\t\tThis is your miles per gallon (mpg): " + oneDecimalDigits.format(mpg));
//displays mpg
//calculates time//
totalTimeHours = distance / AVERAGE_SPEED;
//below line displays total time in hours to 3 decimal places
System.out.println ("\n\t\tThis is was your time in hours: "
+ threeDecimalDigits.format(totalTimeHours));
//extracts hours from time in hours
hours = (int)totalTimeHours;
minutes = Math.round((totalTimeHours - hours) * 60);
//prints total time in hrs and minutes
System.out.println ("\t\tThis is the total time in hours and minutes: " + hours
+ " hours and " + minutes + " minutes");
System.out.println ("\t" + DASHES);
}