2013-09-24 49 views
0

我正在介紹Java編程,我有下面的任務。我認爲我的代碼是正確的,但我得到了錯誤的答案。我需要找出每輛車的總成本,並「購買」更便宜的一輛。假設我旅行50000里程:驅動= 50000 如何解決這個邏輯錯誤(初學者)?

  • 收購價格爲汽車

    • 燃油成本= $ 4
    • 數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 我不明白我得到了錯誤的答案。 注意:我無法發佈圖片(出於聲譽原因)和視頻,但我願意在需要時提供該信息。 謝謝。

  • 回答

    1

    的問題是在這條線:

    System.out.println(total4Car1 + gasCost4Car1); 
    

    total4Car1已經包含gasCost4Car1

    這裏是一個demo on ideone印刷34000

    0

    total4car1不小於total4car2,因此它打印汽車2的總數,即purchaseprice2 + gascost4car2,然後再在System.out.println(purchasePrice2 + gasCost4Car2); // just to see the output for car 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); 
        } 
    }