Dan*_* S. 0 java double int casting
我目前遇到了代码问题.我必须将小时和分钟声明为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);
}
Run Code Online (Sandbox Code Playgroud)
替换:
minutes = Math.round((totalTimeHours - hours) * 60);
Run Code Online (Sandbox Code Playgroud)
用:
minutes = Math.round((float)((totalTimeHours - hours) * 60));
Run Code Online (Sandbox Code Playgroud)
要么
minutes = (int)Math.round((totalTimeHours - hours) * 60);
Run Code Online (Sandbox Code Playgroud)
数学中有两种方法
long Math.round(double);
int Math.round(float);
Run Code Online (Sandbox Code Playgroud)
你正在传递一个双参数,所以你调用一个返回long的那个并将它分配给一个int,这是错误的.