gpt4 book ai didi

Java 运费计算器

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:53 24 4
gpt4 key购买 nike

我正在开发一个运费计算器,我已经把它全部写好了,但我有一个小问题。每 500 英里我需要收取 x 金额。它可以工作,但如果里程是 500 英里的倍数,则需要另外充电 500 英里。我明白为什么它会按照我写的方式这样做,但我不知道还有什么方法可以让行驶 750 英里的前 500 英里收取 2 次费用,然后其余的则收取 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);
}

}

最佳答案

使用Math.ceil :

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases:

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument.

  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

  • If the argument value is less than zero but greater than -1.0, then the result is negative zero.

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

表达式 milesnum/500.0 将返回 double 值(与 milesnum/500 不同,后者将返回 int)。然后,math.ceil 会将该值向上舍入。

如果 milesnum == 500milesnum/500.0 为 1,四舍五入为 1。

如果 milesnum == 550milesnum/500.0 为 1.1,四舍五入为 2。

关于Java 运费计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32832735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com