计算燃气里程效率

时间:2014-10-03 16:51:37

标签: java variables math double

由于优质汽油比普通汽油贵,我需要计算必须使用优质汽油的汽油里程,以弥补与普通汽油之间的成本差异。该值由gasmileageRequired变量表示。

问题:我是否正确计算了gasmileageRequired变量?

    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.Scanner;

    public class GasMileage {
    public static void main(String[] args) {

        //Variable declarations
        Scanner scan = new Scanner(System.in);
        NumberFormat numFmt = new DecimalFormat("##.###");
        NumberFormat costFmt = DecimalFormat.getCurrencyInstance();

        double tankSize = 0;
        final double regularCost;
        final double premiumCost;
        double regularGasMileage = 0;


        //User enters gas tank size
        System.out.print("What is the size of your gas tank? (in gallons) ");
        tankSize = scan.nextDouble();

        //User enters price of regular gasoline
        System.out.print("What is the cost of regular gasoline per gallon? (in $) ");
        regularCost = scan.nextDouble();

        //User enters price of premium gasoline
        System.out.print("What is the cost of premium gasoline per gallon? (in $) ");
        premiumCost = scan.nextDouble();

        //User enters cars' gas mileage
        System.out.print("What is your cars' gas mileage on regular gasoline? (miles/gallon) ");
        regularGasMileage = scan.nextDouble();

        //Variable declarations
        double totalregularCost = regularCost * tankSize;
        double totalpremiumCost = premiumCost * tankSize;
        double costDifference = totalpremiumCost - totalregularCost;
        double gasmileageRequired = regularGasMileage + (premiumCost/costDifference);
        scan.close();

        //Begin output
        System.out.println("\nGas tank size: " + tankSize + " gallons");
        System.out.println("\nTotal cost of regular gasoline: " + costFmt.format(totalregularCost) + "\nGas mileage (regular): " + numFmt.format(regularGasMileage) + " miles/gallon");
        System.out.println("\nTotal cost of premium gasoline: " + costFmt.format(totalpremiumCost) + "\nGas mileage required to make up for cost increase: " +
        numFmt.format(gasmileageRequired) + " miles/gallon");
    }
}

1 个答案:

答案 0 :(得分:0)

gasmilageRequired正在计算中,是的。它应该告诉你为了弥补价格差异你需要多少MPG。