This question already has answers here:
Division of integers in Java [duplicate]
                                
                                    (7个答案)
                                
                        
                                3个月前关闭。
            
                    
我有这样的课:

public class Test {
    public static void main(String[] args) {
        CarPurchaseV2 car = new CarPurchaseV2(23, "Model", 25000, 24, 3.9);
        System.out.println(car.computeFiveYearCost(car.computeMonthlyPayment()));
    }
}

class CarPurchaseV2 {
    private int carMileage;
    private String carMakeModel;
    private double purchasePrice;
    private int loanMonths;
    private double interestRate;

    public double computeMonthlyPayment()  {
        double monthlyRate = (interestRate/100)/12;
        double factor = Math.exp(loanMonths * Math.log(1 + monthlyRate));

        return (factor * monthlyRate * purchasePrice) / (factor - 1);
    }

    public double computeFiveYearCost(double monthlyPayment)  {
        int MILES_PER_YEAR = 12000;
        double COST_PER_GALLON = 2.75;

        double totalLoanCost = monthlyPayment * loanMonths;
        double totalGasCost = (MILES_PER_YEAR / carMileage) * COST_PER_GALLON * 5;

        return totalLoanCost + totalGasCost;
    }

    public CarPurchaseV2(int carMileage, String carMakeModel,
                         double purchasePrice, int loanMonths, double interestRate)  {
        this.carMileage = carMileage;
        this.carMakeModel = carMakeModel;
        this.purchasePrice = purchasePrice;
        this.loanMonths = loanMonths;
        this.interestRate = interestRate;
    }
}


当我为carMileage = 23purchasePrice = 25000loanMonths = 24interestRate = 3.9%运行它时,我得到了$33192.01,而我需要获得(教科书答案)$33202.17。我不明白这段代码有什么问题。当我运行调试器时,monthlyPayment = 1084.5106749708948totalLoanCost = 26028.256199301475

编辑:编辑代码为MRE。

最佳答案

可变carMileage应该是double。因为当您执行除法时,您会失去浮动部分。

将变量更改为双精度类型

private double carMileage;


或将除法结果加倍

double totalGasCost = ((double) MILES_PER_YEAR / carMileage)* COST_PER_GALLON * 5;

10-06 10:43