Java乘法运算行为 [英] Java multiply operation behavior

查看:519
本文介绍了Java乘法运算行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个方法将给定数字从天转换为毫秒:

I wrote a method to convert a given number from days to milliseconds:

private long expireTimeInMilliseconds;
...
public void setExpireTimeInDays(int expireTimeInDays)
{
   expireTimeInMilliseconds = expireTimeInDays * 24 * 60 * 60 * 1000;
}

我很难弄明白我做错了什么。现在我的问题是:
这个错误是如此明显吗?

I had a hard time to figure out what I did wrong. Now my question: Is that error so obvious ?

更正方法:

private long expireTimeInMilliseconds;
...
public void setExpireTimeInDays(int expireTimeInDays)
{
   expireTimeInMilliseconds = ((long) expireTimeInDays) * 24 * 60 * 60 * 1000;
}

如果我在计算之前没有将整数转换为long,我会得到一个完全错误的结果。

If I don't convert the integer to long before calculating, I get a complete wrong result.

推荐答案

这是显而易见的吗?我想这取决于你使用Java多长时间以及你需要多少次处理毫秒。当然,它应该可以持续大约24天......

Is it obvious? I guess it depends on how long you've been using Java and how many times you've had to deal with milliseconds. Of course, it should be okay for up to about 24 days...

我认为最大的提示应该是 System.currentTimeMillis() 返回 long 。这是一个很好的迹象,可以在几毫秒内变大。你设置的变量类型也应该是一个很好的提示。

I think the biggest hint should be that System.currentTimeMillis() returns a long. That's a good indication that a number of milliseconds can get big. The type of the variable you're setting should be a good hint too.

当然,你知道如果你用int进行算术运算,结果将是 int ,并在溢出时进行环绕。这是否足够明显可以辩论,但这将是一个非常毫无意义的讨论。在C#中,如果你打开溢出检查,你很快就会发现错误 - 但是没有多少开发人员这样做(事实上,我不是,但我可能应该这样做)。

Of course, you've also got to know that if you do arithmetic operations with ints, the result will be int with wrap-around on overflow. Whether that's sufficiently obvious or not could be debated, but it would be a pretty pointless discussion. In C# if you turned overflow checking on, you'd have found the bug pretty quickly - but then not many developers do that (indeed, I don't although I probably should).

这篇关于Java乘法运算行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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