为什么整数除法代码给出错误的答案?
我在Java中有一个非常简单的除法(它是产品数量/每小时的产量),但是每当我进行这个除法时,我都会遇到奇怪的错误:
float res = quantity / standard;
我已经用几个值尝试了上面的除法,但我总是得到错误,但是我已经尝试过其他地方并得到了正确的结果是:
世界各地:
13.6 = 6800 / 500;
Java:
13.0 = 6800 / 500;
我研究了 BigDecimal 和 BigInteger,但是我还没有找到用它们创建此除法的方法,还有其他方法可以进行此除法吗在Java中没有精度错误?
任何帮助将不胜感激。
I have a very simple division in Java (it's a product quantity / production per hour), however whenever I make this division I get strange errors:
float res = quantity / standard;
I have tried the above division with several values and I always get errors, however the one that I've tried everywhere else and gotten right was this:
Everywhere in the world:
13.6 = 6800 / 500;
Java:
13.0 = 6800 / 500;
I've researched BigDecimal and BigInteger, however I haven't found a way to create this division with them, is there any other way to do this division in Java without having precision errors??
Any help will be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在对整数进行除法,这意味着您正在使用整数除法。
在整数除法中,结果的小数部分被丢弃。
尝试以下操作:
上面强制将分子视为浮点型,这反过来又促使分母也浮点型,并且执行浮点除法而不是整数除法。
请注意,如果您正在处理文字,则可以更改
为包含
f
后缀以使分母成为浮点数:You're dividing integers, which means that you're using integer division.
In integer division the fractional part of the result is thrown away.
Try the following:
The above forces the numerator to be treated as a
float
which in turn promotes the denominator to float as well, and a float-division is performed instead of an int-division.Note that if you're dealing with literals, you can change
to include the
f
suffix to make the denominator a float:如果您担心精度,我建议使用 double ,它的精度位数超过两倍。然而,浮点数只能准确地表示 0.5 的和或幂的分数。这意味着 0.6 仅近似表示。如果进行适当的舍入,这不一定是问题。
或者
If you concerned about precision I would suggest using
double
which has more than double the number of digits of precision. However floating point only accurately represents fractions which are a sum or powers of 0.5. This means 0.6 is only approximately represented. This doesn't have to be a problem with appropriate rounding.or
就我而言,我这样做:
而不是“正确”:
In my case I was doing this:
Instead of the "correct" :
您好,尝试一下这个,它可能有助于满足您的要求
hi try this one it may help ful your requirement