根据数量计算折扣价的简单逻辑

时间:2014-12-18 06:43:50

标签: php

我正在使用只有一种产品的购物车,其中我必须为每一件物品提供50%的折扣(“对于每个以全价购买的单位,你可以以半价购买另一个”)。

例如,假设产品价格为10美元。

if 1 qty Total Price = $10 ($10).
if 2 qty Total Price = $15 ($10 + $5).
if 3 qty total price = $25 ($10 + $5 + $10).
if 4 qty total price = $30 ($10 + $5 + $10 + $5).
if 5 qty total price = $40 ($10 + $5 + $10 + $5 + $10).
and so on ...

那么根据物品的数量找到折扣的逻辑是什么?

2 个答案:

答案 0 :(得分:1)

如果基本价格为unitcost,那么全价将为:

quantity * unitcost

每秒计算50%的折扣可以计算为(项目的一半,向下舍入,乘以成本的一半):

int (quantity / 2) * (unitcost / 2)

制作最终价格:

(quantity * unitcost) - (int (quantity / 2) * (unitcost / 2))

以下程序(使用Python,我的快速和脏代码样本的首选语言)显示了测试数据的实际效果:

unitcost = 10
for quant in range(1,10):
    print "%2d -> $%d" % (quant, quant*unitcost-(int(quant/2)*unitcost/2))

根据您的示例使用unitcost作为10,您可以获得每个数量的以下费用(右侧的注释表示额外单位费用的多少):

 1 -> $10    + 10
 2 -> $15    +  5
 3 -> $25    + 10
 4 -> $30    +  5
 5 -> $40    + 10
 6 -> $45    +  5
 7 -> $55    + 10
 8 -> $60    +  5
 9 -> $70    + 10

答案 1 :(得分:0)

虽然它看起来很复杂,但效果很好......

echo $total = (floor($quantity/2)*($price/2)) + (($quantity - (floor($quantity/2)))*$price);