为什么整数除法码给出了错误的答案? [英] Why does integer division code give the wrong answer?

查看:198
本文介绍了为什么整数除法码给出了错误的答案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

float res = quantity / standard;

我已经尝试了上述除法,并且总是得到错误,但是,已经在其他地方尝试过,并得到正确的是这样的:



在世界各地:

  13.6 = 6800/500; 

Java:

  13.0 = 6800/500; 

我研究了BigDecimal和BigInteger,但是我还没找到一种方法来创建这个分区他们,有没有其他的方式来做这个分裂在Java中没有精度错误??

任何帮助将不胜感激。

解决方案

您正在分割整数,这意味着您正在使用整数除法。


$ b $

尝试以下操作:

<

在整数除法中,结果的小数部分被丢弃。 p $ p> float res =(float)quantity / standard;
^^^^^^^

上面的分子被视为一个分子 float 这反过来促进了分母的浮动,并且执行了浮点除法而不是整数除法。


$ b $注意,如果你正在处理文字,你可以改变

  float f = 6800/500; 

包含 f 后缀分母a float:

  float f = 6800f / 500; 
^


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.

解决方案

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:

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

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;

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

float f = 6800f / 500;
              ^

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

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