如何解决这个逻辑错误(初学者)?

时间:2013-09-24 00:12:59

标签: java if-statement runtime-error bluej

我正在介绍Java编程,我有以下作业。我认为我的代码是正确的,但我得到了错误的答案。我需要找到每辆车的总成本,然后“买”更便宜的车。假设我旅行了50000英里:

  • 燃料成本= $ 4
  • 里程数= 50000
  • 汽车购买价格1 = $ 15000
  • 汽车购买价格2 = $ 30000
  • 汽车的Mpg 1 = 10
  • 汽车的Mpg 2 = 50

燃气成本=(英里驱动/ Mpg)*燃料成本

总成本=购买价格+燃气成本

这是我的代码:

public class Test
{
    public static void main(String[] args)
    {
        int milesDriven = 50000;
        int mpg1 = 10;
        int mpg2 = 50;
        int pricePerGallon = 4;
        int purchasePrice1 = 15000;
        int purchasePrice2 = 30000;
        int gasCost4Car1 = (milesDriven / mpg1) * pricePerGallon;
        int gasCost4Car2 = (milesDriven / mpg2) * pricePerGallon;
        int total4Car1 = (purchasePrice1 + gasCost4Car1);
        int total4Car2 = (purchasePrice2 + gasCost4Car2);

        if(total4Car1 < total4Car2) 
        {
            System.out.println(total4Car1 + gasCost4Car1);
        }
            else
            {
            System.out.println(purchasePrice2 + gasCost4Car2);
        }

       System.out.println(purchasePrice2 + gasCost4Car2); // just to see the output for car 2
    }
}

我得到的输出是34000 而且我认为对于汽车1来说,输出应该是35000 并且车2的输出应为34000 我不明白我得到了错误的答案。 注意:我不能发布图片(出于声誉原因)或视频,但我愿意在需要时提供该信息。 谢谢。

3 个答案:

答案 0 :(得分:1)

问题在于这一行:

System.out.println(total4Car1 + gasCost4Car1);

total4Car1已包含gasCost4Car1

这是demo on ideone打印34000

答案 1 :(得分:0)

total4car1不小于total4car2,因此它打印汽车2的总数,即purchaseprice2 + gascost4car2,然后再次在System.out.println(purchasePrice2 + gasCost4Car2); // just to see the output for car 2打印。应该输出什么?

答案 2 :(得分:0)

稍微清理一下,给出正确的结果:

public static void main(String[] args) {
    int milesDriven = 50000;
    int mpg1 = 10;
    int mpg2 = 50;
    int pricePerGallon = 4;
    int purchasePrice1 = 15000;
    int purchasePrice2 = 30000;
    int gasCost4Car1 = milesDriven / mpg1 * pricePerGallon;
    int gasCost4Car2 = milesDriven / mpg2 * pricePerGallon;
    int total4Car1 = purchasePrice1 + gasCost4Car1;
    int total4Car2 = purchasePrice2 + gasCost4Car2;

    System.out.println("Total car 1: " + total4Car1);
    System.out.println("Total car 2: " + total4Car2);

    if (total4Car1 < total4Car2) {
        System.out.println("Car 1 is cheaper: " + total4Car1);
    } else {
        System.out.println("Car 2 is cheaper: " + total4Car2);
    }
}