From c03a8c257537546bf753009d882a89d6a8a41992 Mon Sep 17 00:00:00 2001 From: longgui <1263913337@qq.com> Date: Thu, 6 Aug 2020 21:29:28 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=87=8F=E4=B9=98=E9=99=A4=E7=9A=84?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 加减乘除代码.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 加减乘除代码.java diff --git a/加减乘除代码.java b/加减乘除代码.java new file mode 100644 index 0000000..c44996e --- /dev/null +++ b/加减乘除代码.java @@ -0,0 +1,39 @@ + +public class Arith +{ + //默认除法运算精度 + private static final int DEF_DIV_SCALE = 10; + //构造器私有化,让这个类不能实例化 + private Arith(){} + //提供精确的加法运算 + public static double add(double v1, double v2) + { + BigDecimal b1 = BigDecimal.valueOf(v1); + BigDecimal b2 = BigDecimal.valueOf(v2); + return b1.add(b2).doubleValue(); + } + //精确的减法运算 + public static double sub(double v1, double v2) + { + BigDecimal b1 = BigDecimal.valueOf(v1); + BigDecimal b2 = BigDecimal.valueOf(v2); + return b1.subtract(b2).doubleValue(); + } + //精确的乘法运算 + public static double mul(double v1, double v2) + { + BigDecimal b1 = BigDecimal.valueOf(v1); + BigDecimal b2 = BigDecimal.valueOf(v2); + return b1.multiply(b2).doubleValue(); + } + //提供(相对)精确的除法运算,当发生除不尽的情况时 + //精确到小数点后10位的数字四舍五入 + public static double div(double v1, double v2) + { + BigDecimal b1 = BigDecimal.valueOf(v1); + BigDecimal b2 = BigDecimal.valueOf(v2); + return b1.divide(b2, DEF_DIV_SCALE, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + +} \ No newline at end of file