我是Java的新手,我们正在根据不同的重量和距离进行运费计算。我们正在练习if-else语句,但我遇到了一个我无法弄清楚的问题。 当我计算不同的重量和距离时,我得到了错误的答案。我认为它与我的数学有关,我似乎无法让程序为距离添加下一个费用,因为它没有使用余数。请帮我理解这一点。
public class ShippingCharges {
private double weight;
private double miles;
public ShippingCharges (double w, double m)
{
weight = w;
miles = m;
}
public double getShippingCharges()
{
double charges;
if (weight <= 2.0)
{ charges = (1.10 * miles / 500);
}
else if ((weight > 2.0) && (weight <= 6.0))
{
charges = (2.20 * (miles / 500 ));
}
else if ((weight > 6.0) && (weight <=10.0))
{
charges = (3.70 * (miles / 500 ));
}
else
{
charges = (4.80 * miles / 500);
}
return charges;
}
}
答案 0 :(得分:3)
根据你所说的我明白问题是你没有将里程/ 500结果四舍五入,试试这个:
public double getShippingCharges()
{
double charges;
if (weight <= 2.0)
{ charges = (1.10 * Math.ceil(miles / 500));
}
else if ((weight > 2.0) && (weight <= 6.0))
{
charges = (2.20 * Math.ceil(miles / 500 ));
}
else if ((weight > 6.0) && (weight <=10.0))
{
charges = (3.70 * Math.ceil(miles / 500 ));
}
else
{
charges = (4.80 * Math.ceil(miles / 500));
}
return charges;
}