如何在Java中实现基于购买数量的动态折扣计算逻辑?
解决方案
首先修正原代码的拼写错误(totalePrice → totalPrice),然后调整折扣计算逻辑,让它能根据购买数量自动计算可享受的折扣次数:
int discountThreshold = 3; // 满3件触发一次折扣 double discountPerThreshold = 3.0; // 每次折扣的金额 int quantityPurchased = 5; // 示例购买数量,可替换为任意值 double itemPrice = 6.0; // 计算原始总价 double totalPrice = itemPrice * quantityPurchased; // 计算可享受的折扣次数:整数除法自动取整,比如5/3=1,6/3=2 int discountCount = quantityPurchased / discountThreshold; // 应用折扣 totalPrice = totalPrice - discountCount * discountPerThreshold; // 可选:输出最终总价 System.out.println("最终总价:" + totalPrice + "€");
关键逻辑说明
- 用
quantityPurchased / discountThreshold计算折扣次数:整数除法会自动舍去小数部分,正好匹配"每满3件减一次"的规则——买5件能享受1次折扣,买6件能享受2次,买2件则无折扣。 - 优化了变量命名,避免原代码中
quantity和quantityItem易混淆的问题,让代码可读性更强。 - 修复了原代码中
totalePrice的拼写错误,避免编译报错。
测试验证
- 购买5件:
6*5 - 1*3 = 27€,符合预期。 - 购买6件:
6*6 - 2*3 = 30€,符合预期。 - 购买2件:
6*2 - 0*3 = 12€,无折扣,符合规则。
内容的提问来源于stack exchange,提问作者bircastri
相关产品推荐
相关产品推荐

