为什么整数除法代码给出错误的答案?

Why does integer division code give the wrong answer?(为什么整数除法代码给出错误的答案?)
本文介绍了为什么整数除法代码给出错误的答案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 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:

世界各地:

13.6 = 6800 / 500;

Java:

13.0 = 6800 / 500;

我研究过 BigDecimal 和 BigInteger,但是我还没有找到用它们创建这种除法的方法,有没有其他方法可以在 Java 中进行这种除法而不会出现精度错误??

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??

任何帮助将不胜感激.

推荐答案

你正在对整数进行除法,这意味着你正在使用整数除法.

You're dividing integers, which means that you're using integer division.

在整数除法中,结果的小数部分被丢弃.

In integer division the fractional part of the result is thrown away.

尝试以下方法:

float res = (float) quantity / standard;
            ^^^^^^^

上面的内容强制将分子视为 float 反过来促进分母也浮动,并且执行浮点除法而不是整数除法.

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

float f = 6800 / 500;

包含 f 后缀以使分母变为浮点数:

to include the f suffix to make the denominator a float:

float f = 6800f / 500;
              ^

这篇关于为什么整数除法代码给出错误的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)