Java中的除法 [英] division in java

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

问题描述

我在Java中有一个简单的部门:

I have a simple division in Java:

float f = 19.7f/100;
System.out.println(f); // 0.19700001

double d = 19.7/100;
System.out.println(d); // 0.19699999999999998

为什么会这样?

推荐答案

这是有史以来最常见的问题之一,因此在这里我要指出几点.

This is one of the most commonly asked questions in anything ever, so I'll put a couple of points down here.

  1. 计算机只能表示有限数量的数字,因此在存储数字并随后对其进行除法时必须四舍五入.这种四舍五入自然会产生错误,但是如果您只想说3位数的精度,那么在您的情况下它们就无关紧要.

  1. Computers can only represent a finite number of digits, so rounding off has to occur when storing numbers and later dividing them. This rounding off produces errors naturally, but if you only want, say, 3 digits of precision, they shouldn't matter in your case.

四舍五入的行为有点不可预测,因为计算机以二进制形式存储数字.因此,虽然19.7是终止小数,但相同的数字是二进制的重复十进制-10011.101100110011001100110011001100110011 ... ...因此,您可以看到在任意点舍入将产生无法从终止小数表达式中预测的行为.

The behavior of rounding off is a bit unpredictable because computers store numbers in binary. So whereas 19.7 is a terminating decimal, the same number is a repeating decimal in binary -- 10011.10110011001100110011001100110011... ... so you can see that rounding off at an arbitrary point will produce behavior that is not predictable from the terminating decimal expression.

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

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