php中计算百分比时如何保证各部和为1?
$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);以上就是PHP中计算百分比时怎么保证各部和为1的内容,更多相关内容请关注PHP中文网(www.php.cn)!
立即学习“PHP免费学习笔记(深入)”;
相关文章:
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号