java - Java 中的运费计算器,得出错误的数字

标签 java rounding

我正在使用 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;

    }

关于java - Java 中的运费计算器,得出错误的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15466172/

相关文章:

java - 循环打印多次

java - 使用 websocket spring 初始化进行长轮询回退

runtime - Java 运行时检查 JDK 功能是否可用

javascript - 在 JavaScript 中添加一周至今 : rounding error or daylight savings?

Java - 按四分之一间隔舍入

java - 返回匹配数组值的索引总和

java - TestNG 中的 alwaysRun 参数

java - 为什么 BigDecimal.stripTrailingZeros() 不总是删除所有尾随零?

sql - 在SQL中舍入到小数点后2位

javascript - 在 JavaScript 中 chop/舍入整数?