2015-09-28 55 views
1

我正在運輸成本計算器,我已經寫了所有,但我有一個小問題。我需要每500英里收取x金額。它可以工作,但是如果里程是500的倍數,那麼另外500英里的費用就會上漲。我明白爲什麼它會按照我寫的方式做,但我不知道如何獲得說750英里的路程才能獲得前500英里的2次收費,然後剩下的收費。爪哇航運成本計算器

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

使用Math.ceil

返回最小的(最接近負無窮大)雙值,該值大於或等於該參數,並等於某個整數 。特殊情況:

  • 如果參數值已經等於數學整數,則結果與參數相同。

  • 如果參數是NaN或無窮大或正零或負零,則結果與參數相同。

  • 如果參數值小於零但大於-1.0,則結果爲負零。

cost = Math.ceil(milesnum/500.0)*multiplier; 

表達milesnum/500.0將返回一個雙(相對於milesnum/500,這將返回一個int)。然後math.ceil將向上取整。

如果milesnum == 500milesnum/500.0是1,其被四捨五入爲1。

如果milesnum == 550milesnum/500.0是1.1,這是舍入成2

+0

確定我明白了。我曾經嘗試過Math.ceil,但我沒有將500改爲500.0。謝謝! –