我是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;
}
}
最佳答案
根据您所说的,我理解的问题是您没有将Miles / 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;
}