java互联网电商商品实时优惠券卷后价格展示多张优惠券需要算取最优的价格为券后价格
实现思路:
-
首先获取商品的原价和所有可用的优惠券信息。
-
遍历每一张优惠券,计算出优惠后的价格。
-
将每一张优惠券优惠后的价格存储到一个数组中。
-
对数组进行排序,取出最小值即为最优价格。
-
将最优价格展示给用户。
代码实现:
假设商品原价为100元,有三张优惠券,分别为满50减10元,满100减30元,满200减50元。
public class CouponDemo {
public static void main(String[] args) {
double price = 100; // 商品原价
double[] discounts = {10, 30, 50}; // 优惠金额
double[] thresholds = {50, 100, 200}; // 满减门槛
double[] prices = new double[discounts.length]; // 存储优惠后的价格
for (int i = 0; i < discounts.length; i++) {
if (price >= thresholds[i]) {
prices[i] = price - discounts[i];
} else {
prices[i] = price;
}
}
Arrays.sort(prices); // 升序排序
System.out.println("最优价格:" + prices[0]); // 取出最小值即为最优价格
}
}
输出结果为:
最优价格:70.0
说明选择满100减30元的优惠券最优,券后价格为70元
原文地址: https://www.cveoy.top/t/topic/cfzV 著作权归作者所有。请勿转载和采集!