Java-将小时数(双精度)转换为分钟数(整数),反之亦然 [英] Java - Converting hours(in double) to minutes(integer) and vice versa

查看:603
本文介绍了Java-将小时数(双精度)转换为分钟数(整数),反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要正确的公式,它将小时转换为分钟,反之亦然。
我已经编写了一个代码,但是它似乎没有按预期工作。
例如:
如果我的小时数= 8.16,则分钟应该是490,但是我得到的结果是489。

I need the correct formula that will convert hours to minutes and vice versa. I have written a code, but it doesn't seem to work as expected. For eg: If I have hours=8.16, then minutes should be 490, but I'm getting the result as 489.

  import java.io.*;
  class DoubleToInt {

  public static void main(String[] args) throws IOException{

  BufferedReader buff = 
  new BufferedReader(new InputStreamReader(System.in)); 
  System.out.println("Enter the double hours:");
  String d = buff.readLine();

  double hours = Double.parseDouble(d);
  int min = (int) ((double)hours * 60);

  System.out.println("Minutes:=" + min);
  }
} 


推荐答案

因为强制转换为 int 截断了小数部分-它没有舍入:

That's because casting to int truncates the fractional part - it doesn't round it:

8.16 * 60 = 489.6

当强制转换为 int ,它变为489。

When cast to int, it becomes 489.

请考虑使用 Math.round() 计算方法:

Consider using Math.round() for your calculations:

int min = (int) Math.round(hours * 60);

注意: double 的准确性有限并且会受到影响来自小余数错误问题,但使用 Math.round() 可以很好地解决该问题,而不必麻烦处理 BigDecimal (我们不是在计算内部

Note: double has limited accuracy and suffers from "small remainder error" issues, but using Math.round() will solve that problem nicely without having the hassle of dealing with BigDecimal (we aren't calculating inter-planetary rocket trajectories here).

仅供参考,要将分钟转换为小时,请使用:

FYI, to convert minutes to hours, use this:

double hours = min / 60d; // Note the "d"

60之后需要 d 使60成为的两倍,否则为 int ,因此您的结果将是 int 也使小时的整数倍。通过将其设置为 double ,您可以将Java向上转换的最小值最小化为用于计算的double,这就是您想要的。

You need the "d" after 60 to make 60 a double, otherwise it's an int and your result would therefore be an int too, making hours a whole number double. By making it a double, you make Java up-cast min to a double for the calculation, which is what you want.

这篇关于Java-将小时数(双精度)转换为分钟数(整数),反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆