java 分钟数,Java-将小时数(双精度)转换为分钟数(整数),反之亦然

博客讨论了在Java中将小时转换为分钟和从分钟转换回小时时遇到的问题。代码示例中,由于类型转换时舍去了小数部分,导致结果不准确。解决方案建议使用Math.round()方法进行四舍五入,以避免丢失精度。同时,给出了将分钟转换回小时的公式,确保结果为双精度浮点数。
摘要由CSDN通过智能技术生成

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);

}

}

解决方案

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

8.16 * 60 = 489.6

When cast to int, it becomes 489.

Consider using Math.round() for your calculations:

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

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"

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值