所以这是我的任务:
一个包裹的邮政公司对第一磅或其一小部分收取 15 美元,对于超过一磅的任何东西收取每磅 10 美元。编写一个打印包裹费用的程序。
变量:
重量
第一次执行:
重量?-12 权重必须是正数。
第二次执行:
重量?0 权重必须为正数。
第三次执行:
重量?2 支付:25.00 美元
第四次执行:
重量?2.8 支付:33.00 美元
第五次执行:
重量?2.07 支付:25.70 美元
这是我到目前为止开发的代码:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
for (double i = 1; i < weight; i = i + .01) {
if (weight > 1) {
output = output + (1 / 10.00);
}
}
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
一切正常,但我不明白为什么(特别是在第四次和第五次执行中)最终输出总是 0.10 美分。谁能帮我达到我需要的准确性?