题目:企业发放的奖金根据利润提成。
利润(I)低于或等于10万元时,奖金可提10%;
利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;
20万到40万之间时,高于20万元的部分,可提成5%;
40万到60万之间时高于40万元的部分,可提成3%;
60万到100万之间时,高于60万元的部分,可提成1.5%;
高于100万元时,超过100万元的部分按1%提成。
从键盘输入当月利润I,求应发放奖金总数?
程序分析
题目要求根据不同利润段来计算奖金,根据利润提成。我们可以通过编写Java程序实现这个目标。
方法一:分段计算奖金
import java.util.Scanner;
public class ProfitBonus {
public static double calculateBonus(double profit) {
double bonus = 0.0;
if (profit <= 100000) {
bonus = profit * 0.1;
} else if (profit <= 200000) {
bonus = 100000 * 0.1 + (profit - 100000) * 0.075;
} else if (profit <= 400000) {
bonus = 100000 * 0.1 + 100000 * 0.075 + (profit - 200000) * 0.05;
} else if (profit <= 600000) {
bonus = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + (profit - 400000) * 0.03;
} else if (profit <= 1000000) {
bonus = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + 200000 * 0.03 + (profit - 600000) * 0.015;
} else {
bonus = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + 200000 * 0.03 + 400000 * 0.015 + (profit - 1000000) * 0.01;
}
return bonus;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the profit: ");
double profit = scanner.nextDouble();
double bonus = calculateBonus(profit);
System.out.println("The bonus is: " + bonus);
}
}
解题思路及优缺点
-
解题思路:
- 根据利润的不同范围,分段计算奖金。
-
优点:
- 简单直观,容易理解和实现。
-
缺点:
- 代码中包含大量重复的计算,不易于维护,扩展性较差。
方法二:使用数组存储奖金比例
import java.util.Scanner;
public class ProfitBonus {
public static double calculateBonus(double profit) {
double[] bonusRates = {0.1, 0.075, 0.05, 0.03, 0.015, 0.01};
double[] thresholds = {100000, 200000, 400000, 600000, 1000000, Double.MAX_VALUE};
double bonus = 0.0;
double remainingProfit = profit;
for (int i = 0; i < bonusRates.length; i++) {
if (remainingProfit <= 0)
break;
double threshold = thresholds[i];
double rate = bonusRates[i];
if (remainingProfit > threshold) {
bonus += threshold * rate;
remainingProfit -= threshold;
} else {
bonus += remainingProfit * rate;
break;
}
}
return bonus;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the profit: ");
double profit = scanner.nextDouble();
double bonus = calculateBonus(profit);
System.out.println("The bonus is: " + bonus);
}
}
解题思路及优缺点
-
解题思路:
- 使用数组存储奖金比例和利润阈值,遍历数组计算奖金。
-
优点:
- 减少了代码重复,提高了代码的可维护性和扩展性。
-
缺点:
- 数组的使用可能稍微增加了复杂度,但对于此问题不明显。
总结与推荐
- 两种方法都能解决问题,方法二更优雅,减少了重复计算,提高了代码的可维护性和扩展性。
- 推荐方法二,因为它避免了重复计算,提高了代码的清晰度和可维护性。如果有更复杂的奖金计算规则,方法二的优势会更明显。