我正在为学校做一个项目,我试图计算一定距离的汽车油耗,但开关总是返回0.我尝试了不同的东西,但它们似乎都没有工作
public Double DetermineFuelConsumption (String Car, Double Kilometers)
{
Double FuelConsumption = 0;
switch (Car)
{
// (14 / 100) ---> Liters per 100 Kilometers
case "LaFerrari":
FuelConsumption = (14 / 100) * Kilometers;
break;
case "Nissan GT-R Nismo":
FuelConsumption = (12 / 100) * Kilometers;
break;
case "Pagani Huayra":
FuelConsumption = (18 / 100) * Kilometers;
break;
case "McLaren P1":
FuelConsumption = (8 / 100) * Kilometers;
break;
case "Lamborghini Aventador":
FuelConsumption = (16 / 100) * Kilometers;
break;
case "Smart":
FuelConsumption = (4 / 100) * Kilometers;
break;
case "Porsche 911":
FuelConsumption = (9 / 100) * Kilometers;
break;
case "Audi R8":
FuelConsumption = (15 / 100) * Kilometers;
break;
}
return FuelConsumption;
}
答案 0 :(得分:7)
您除以100的所有数字都将为0。
这是整数除法:整数除以整数的结果总是整数。您需要指定您的数字是浮点类型:
public Double DetermineFuelConsumption (String Car, Double Kilometers)
{
Double FuelConsumption = 0;
switch (Car)
{
// (14 / 100) ---> Liters per 100 Kilometers
case "LaFerrari":
FuelConsumption = (14d / 100d) * Kilometers;
break;
case "Nissan GT-R Nismo":
FuelConsumption = (12d / 100d) * Kilometers;
break;
case "Pagani Huayra":
FuelConsumption = (18d / 100d) * Kilometers;
break;
case "McLaren P1":
FuelConsumption = (8d / 100d) * Kilometers;
break;
case "Lamborghini Aventador":
FuelConsumption = (16d / 100d) * Kilometers;
break;
case "Smart":
FuelConsumption = (4d / 100d) * Kilometers;
break;
case "Porsche 911":
FuelConsumption = (9d / 100d) * Kilometers;
break;
case "Audi R8":
FuelConsumption = (15d / 100d) * Kilometers;
break;
}
return FuelConsumption;
}
这里,d
后缀指定这些数字是双精度数,而不是整数。
答案 1 :(得分:3)
试
FuelConsumption = (14d / 100d) * Kilometers;
答案 2 :(得分:3)
你试图划分2个整数(a / b),以防 a< b 将是 0.some-number 的分数,而舍入为int ,这意味着0.然后乘以0 *公里。你看到了这张照片。
改为将其更改为(14 / 100d)
。