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