如上图,电费计费规则,算法如下:
$rules = [
330 => [0,100],
300 => [100,300],
280 => [300,500],
220 => [500,1000],
150 => [1000,2000],
80 => [2000, PHP_INT_MAX],
];
function calc($used,$rules){
$sum = 0;
foreach ($rules as $key => $value){
// 大于计费段
if($used < $value[0]) break;
// 累加前期计费
if($used >= $value[1]) {
$sum += $key * ($value[1] - $value[0]);
}
// 在最后计费段内
if($value[0] < $used && $used <= $value[1]){
$sum += ($used - $value[0]) * $key;
}
}
return round($sum, 2);
}
echo calc(700,$rules);
最后得到193000;
标签:used,rules,sum,value,阶梯,300,算法,计费 From: https://www.cnblogs.com/wujf-myblog/p/16707792.html