【问题标题】:How to solve this logical error (beginner)?如何解决这个逻辑错误(初学者)?
【发布时间】:2013-09-29 00:56:16
【问题描述】:

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

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

汽油成本 =(行驶里程 / Mpg)* 燃料成本

总成本 = 购买价格 + gas 成本

这是我的代码:

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 我不明白我得到了错误的答案。 注意:我不能发布图片(出于声誉原因)或视频,但如果需要,我愿意提供这些信息。 谢谢。

【问题讨论】:

    标签: java if-statement runtime-error bluej


    【解决方案1】:

    问题出在这一行:

    System.out.println(total4Car1 + gasCost4Car1);
    

    total4Car1 已经包含gasCost4Car1

    这是一个demo on ideone 打印34000

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        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);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2018-04-21
          • 2023-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-09
          • 2021-09-19
          • 2017-04-15
          相关资源
          最近更新 更多