Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何修复PracticeIt类继承性舍入错误?_Java_Class_Inheritance - Fatal编程技术网

Java 如何修复PracticeIt类继承性舍入错误?

Java 如何修复PracticeIt类继承性舍入错误?,java,class,inheritance,Java,Class,Inheritance,如何修复PracticeIt类继承性舍入错误?显然,它只在getDiscountPercent()方法中出现故障 它不会返回16.6421928536466,而是返回16.64219285364659 错误为0.00000000000001,这完全符合浮点错误的原因。如果使用double或float值,则会遇到这种不精确性(这是不将=与双值一起使用的参数)。如果您不能接受,请使用BigDecimal。某些十进制值(例如1.3)只能以二进制形式精确表示,并具有无限重复的位模式。这就像一个整数除以另

如何修复PracticeIt类继承性舍入错误?显然,它只在getDiscountPercent()方法中出现故障

它不会返回16.6421928536466,而是返回16.64219285364659


错误为
0.00000000000001
,这完全符合浮点错误的原因。如果使用
double
float
值,则会遇到这种不精确性(这是不将
=
与双值一起使用的参数)。如果您不能接受,请使用
BigDecimal
。某些十进制值(例如1.3)只能以二进制形式精确表示,并具有无限重复的位模式。这就像一个整数除以另一个整数得到一个有理商,在小数点后有一个无限重复的数字模式。显然,
double
中没有无限位,因此它被舍入到最接近的可能表示形式。
public class DiscountBill extends GroceryBill{
    boolean p;
    double totalD;
    double total2;
    double total;
    int count;
    
    
    public DiscountBill(Employee clerk, boolean preferred){
        super(clerk);
        p = preferred;
    }
    
    public void add(Item i){
        super.add(i);
            total2 += i.getPrice();
        if(p){
            totalD+=i.getDiscount();
            total += (i.getPrice() - i.getDiscount());
            if(i.getDiscount() > 0.000){
                count++;
            }
            
        }else{
            total+= i.getPrice();
        }
    }
    public int getDiscountCount(){
       return count;
    }
    public double getDiscountAmount(){
        return totalD;
    }
    public double getDiscountPercent(){
         return 100.0 * (total2-total) /total2;
    }
    public double getTotal(){
        return (double)Math.round(total * 100d) / 100d;
    }
}