将int转换为double Java

时间:2013-06-06 16:33:39

标签: java casting int double

我目前的代码存在问题。 我必须将小时和分钟声明为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);

  }

2 个答案:

答案 0 :(得分:5)

替换

minutes = Math.round((totalTimeHours - hours) * 60);

。通过

minutes = Math.round((float)((totalTimeHours - hours) * 60));

minutes = (int)Math.round((totalTimeHours - hours) * 60);

Math中有两种方法轮次

long Math.round(double);
int Math.round(float);

你正在传递一个双参数,所以你调用一个返回long的那个并将它分配给一个int,这是错误的。

答案 1 :(得分:0)

我没有阅读您的所有代码,但这应该有助于解决您在文中描述的问题:

    double dTime = 6.555;
    int hours = (int) dTime;
    int minutes = (int) ((dTime - hours) * 60);
    System.out.println(hours + ":" + minutes); // prints 6:33