我正在介绍Java编程,我有以下作业。我认为我的代码是正确的,但我得到了错误的答案。我需要找到每辆车的总成本,然后“买”更便宜的车。假设我旅行了50000英里:
燃气成本=(英里驱动/ 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 我不明白我得到了错误的答案。 注意:我不能发布图片(出于声誉原因)或视频,但我愿意在需要时提供该信息。 谢谢。
答案 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);
}
}