PHP头条
热点:

PHP中计算百分比时怎么保证各部和为1


PHP中计算百分比时如何保证各部和为1?
本帖最后由 Jasmine_xiaocao 于 2013-05-18 09:51:53 编辑

$total = $a+$b+$c+$d;

$percentA = ceil($a*100.0/$total);
$percentB = ceil($b*100.0/$total);
$percentC = ceil($c*100.0/$total);
$percentD = ceil($d*100.0/$total);



上面的代码似乎无法确保最后的总和是100%


$percentD = 100-$percentA-$percentB-$percentC;

除了这种方法,有其他方法吗? 分享到:
------解决方案--------------------
$a = array(1,2,3,3);
$total = array_sum($a);
array_walk($a, function(&$item, $key, $prefix) { $item = round($item*100/$prefix); }, $total);
if($d = (100 - array_sum($a))) $a[rand(0, count($a)-1)] += $d;
print_r($a);

www.phpzy.comtrue/phprm/6577.htmlTechArticlePHP中计算百分比时怎么保证各部和为1 PHP中计算百分比时如何保证各部和为1? 本帖最后由 Jasmine_xiaocao 于 2013-05-18 09:51:53 编辑 $total=$a+$b+$c+$d; $percentA=ceil($a*100.0/$total); $percentB=ceil($b*100...

相关文章

相关频道:

PHP之友评论

今天推荐