[英]Convert int to double Java
我的代碼目前有問題。 我必須將小時和分鍾聲明為int,將totalTimeHours聲明為double。 totalTimeHours用於存儲以小時為單位的總時間,例如6.555小時。 例如,我正在處理的問題需要在幾小時和幾分鍾內找到答案。 6小時36分鍾。 對於我的最后一次運行,我需要使用14.7加侖汽油和359.5加侖汽油。 我使用小時=(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);
}
更換 :
minutes = Math.round((totalTimeHours - hours) * 60);
與 :
minutes = Math.round((float)((totalTimeHours - hours) * 60));
要么
minutes = (int)Math.round((totalTimeHours - hours) * 60);
數學中有兩種方法
long Math.round(double);
int Math.round(float);
您傳入了double參數,因此您調用了返回long的參數,並將其分配給int,那是錯誤的。
我沒有閱讀所有代碼,但這應該可以解決您在文字中描述的問題:
double dTime = 6.555;
int hours = (int) dTime;
int minutes = (int) ((dTime - hours) * 60);
System.out.println(hours + ":" + minutes); // prints 6:33
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.