这个java程序的输出略有偏差?

时间:2012-09-10 06:45:04

标签: java

Java代码:

public class Car {

    //variables
    int myStartMiles;
    int myEndMiles;
    double myGallonsUsed;
    int odometerReading;
    double gallons;

    //constructors
    public Car(int odometerReading) {
        this.myStartMiles = odometerReading;
        this.myEndMiles = myStartMiles;
    }

    //methods
    public void fillUp(int odometerReading, double gallons) {
        this.myEndMiles = odometerReading;
        this.gallons = gallons;
    }

    public double calculateMPG() {
        int a = (this.myEndMiles - this.myStartMiles);
        return ((a) / (this.gallons));
    }

    public void resetMPG() {
        myGallonsUsed = 0;
        this.myStartMiles = myEndMiles;
    }

    public static void main(String[] args) {
        int startMiles = 15;
        Car auto = new Car(startMiles);

        System.out.println("New car odometer reading: " + startMiles);
        auto.fillUp(150, 8);
        System.out.println("Miles per gallon: " + auto.calculateMPG());
        System.out.println("Miles per gallon: " + auto.calculateMPG());
        auto.resetMPG();
        auto.fillUp(350, 10);
        auto.fillUp(450, 20);
        System.out.println("Miles per gallon: " + auto.calculateMPG());
        auto.resetMPG();
        auto.fillUp(603, 25.5);
        System.out.println("Miles per gallon: " + auto.calculateMPG()); 
    }
}

我正试图让它工作,但我无法获得所需的输出。

期望的结果是:

New car odometer reading: 15
Miles per gallon: 16.875
Miles per gallon: 16.875
Miles per gallon: 10.0
Miles per gallon: 6.0

我得到了:

New car odometer reading: 15
Miles per gallon: 16.875
Miles per gallon: 16.875
Miles per gallon: 15.0
Miles per gallon: 6.0

你能告诉我代码有什么问题吗?我试图在纸上手动运行它。

1 个答案:

答案 0 :(得分:1)

问题出在您的fillUp方法中。特别是这一行:

this.gallons = gallons;

应该是:

this.gallons += gallons;

由于您要分配而不是添加,因此在第三种情况下输出错误,因为:

auto.fillUp(350, 10);
auto.fillUp(450, 20);

gallons设置为10,然后使用20覆盖,而不是添加10,然后添加20,共计30 }。

编辑:您的gallons = 0;方法中还需要resetMPG。目前你设置myGallonsUsed = 0,但该变量未被使用,所以我不知道你为什么要这样做。