代码
private static void testAddition() {
double a = 2.525;
double b = 2.085714285714286;
double c = 1.8142857142857143;
System.out.println("测试交换律:");
double abc = a + b + c;
double acb = a + c + b;
System.out.println("a + b + c: " + abc);
System.out.println("a + c + b: " + acb);
System.out.println("测试结合律:");
double ABc = (a + b) + c;
double aBC = a + (b + c);
System.out.println("(a + b) + c: " + ABc);
System.out.println("a + (b + c): " + aBC);
System.out.println("其他:");
double bc = b + c;
double cb = c + b;
System.out.println("b + c: " + bc);
System.out.println("c + b: " + cb);
double a_bc = a + (b + c);
double a_cb = a + (c + b);
System.out.println("a + (b + c): " + a_bc);
System.out.println("a + (c + b): " + a_cb);
}
运行结果
可以看出,由于double类型的精度损失,带来了微小误差,如果使用四舍六入五成双算法保留两位小数,6.425 约为 6.42,6.425000000000001 约为 6.43
网友评论