Java中的四舍五入误差

Java中的四舍五入误差

While writing codes we all do various mistakes that lead us to errors like overflow errors and syntax errors. Rounding-off error is one of the common errors that may result in a wrong solution for a given mathematical problem. Generally, this error occurs when we work with floating point numbers.

在这篇文章中,我们将探讨这个问题的原因,并试图找到一种摆脱这种错误的方法。

舍入误差

Floating Point Types

它们也被称为实数,并且在计算需要分数值时使用。它代表具有小数点的数字。例如,表示1/5即0.2的结果,正弦和余弦的结果也需要小数点。

在Java中,有两种类型的浮点数 -

  • 浮点型 - 它可以存储最大32位的单精度值。我们使用 'float' 关键字来声明它。

  • Double − 它的大小比float大,可以存储最大64位的双精度值。它使用'double'关键字声明。

让我们讨论一个例子,在这个例子中我们可能会遇到一个四舍五入误差,然后我们将理解原因,并提供正确处理它的解决方案。

Example 1

public class Main{ public static void main(String[] args) { double data1 = 0.30; double data2 = 0.20 + 0.10; System.out.println("Value after addition: " + data2); System.out.println(data1 == data2); double data3 = 0.50; double data4 = 0.10 + 0.10 + 0.10 + 0.10 + 0.10; System.out.println("Value after addition: " + data4); System.out.println(data3 == data4); } } 登录后复制