根據利潤區間分級提成:
import java.util.Scanner;
public class BonusCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("輸入當月利潤(萬元):");
double profit = sc.nextDouble(); // 單位:萬元
double bonus = 0;
if (profit <= 10) {
bonus = profit * 0.10;
} else if (profit <= 20) {
bonus = 10 * 0.10 + (profit - 10) * 0.075;
} else if (profit <= 40) {
bonus = 10 * 0.10 + 10 * 0.075 + (profit - 20) * 0.05;
} else if (profit <= 60) {
bonus = 10 * 0.10 + 10 * 0.075 + 20 * 0.05 + (profit - 40) * 0.03;
} else if (profit <= 100) {
bonus = 10 * 0.10 + 10 * 0.075 + 20 * 0.05 + 20 * 0.03 + (profit - 60) * 0.015;
} else {
bonus = 10 * 0.10 + 10 * 0.075 + 20 * 0.05 + 20 * 0.03 + 40 * 0.015 + (profit - 100) * 0.01;
}
System.out.printf("應發獎金:%.2f 萬元%n", bonus);
}
}
List 存儲區間邊界與稅率,便於維護擴充。BigDecimal 避免浮點誤差。static class Bracket { double limit; double rate; }
static final Bracket[] BRACKETS = {
{10, 0.10}, {20, 0.075}, {40, 0.05}, {60, 0.03}, {100, 0.015}, {Double.MAX_VALUE, 0.01}
};
public static double calcBonus(double profit) {
double bonus = 0, prev = 0;
for (Bracket b : BRACKETS) {
if (profit > b.limit) {
bonus += (b.limit - prev) * b.rate;
prev = b.limit;
} else {
bonus += (profit - prev) * b.rate;
break;
}
}
return bonus;
}
資料驅動方式更符合開放封閉原則(OCP),新增區間只需修改陣列。