我正在处理运费计算器,我已经写好了但我有一点问题。我需要每500英里收取x金额。它可以工作,但如果里程是500的倍数,那么它将再次收取另外500英里的费用。我理解为什么它按照我写的方式来做,但我不知道怎么说750英里才能获得前500英里的其他费用,然后是其他费用。
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "This program will ask you to enter the weight\n" +"of your package and how many miles it will travel.\n" +"It will then calculate the shipping cost for you.","Greeting",1);
String weight = JOptionPane.showInputDialog(null, "Please enter the weight of your package in pounds such as 5.25.", "Weight", 1);
Double weightnum = Double.parseDouble(weight);
Double overweight = weightnum-10;
String miles = JOptionPane.showInputDialog(null, "You have entered " +weightnum +" lbs.\n" +"Please enter in whole numbers how many miles your package needs to travel such as 250.", "Distance", 1);
int milesnum = Integer.parseInt(miles);
if (milesnum <500)
{
milesnum=0;
}
Double cost;
if (weightnum < 2)
{
cost = (milesnum/500+1)*1.10;
}
else if (weightnum < 6)
{
cost = (milesnum/500+1)*2.50;
}
else if (weightnum < 10)
{
cost = (milesnum/500+1)*3.90;
}
else
{
cost = (milesnum/500+1)*(4.00+(overweight*.5));
}
String strcost= String.format("%.2f", cost);
JOptionPane.showMessageDialog(null, "It will cost $" +strcost +" to ship your " +weightnum +" lbs package " +miles +" miles.\n" +"Have a nice day!", "Cost", 1);
System.exit(0);
}
}
答案 0 :(得分:0)
使用Math.ceil
:
返回大于或等于参数且等于数学整数的最小(最接近负无穷大)double值。特殊情况:
如果参数值已经等于数学整数,那么结果与参数相同。
如果参数为NaN或无穷大或正零或负零,则结果与参数相同。
如果参数值小于零但大于-1.0,则结果为负零。
cost = Math.ceil(milesnum/500.0)*multiplier;
表达式milesnum/500.0
将返回一个double(而不是milesnum/500
,它将返回一个int)。然后math.ceil
将该值向上舍入。
如果milesnum == 500
,milesnum/500.0
为1,则舍入为1.
如果milesnum == 550
,milesnum/500.0
为1.1,则舍入为2。