You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:20:50