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

PHP中文网
Release: 2023-02-28 13:28:02
Original
3172 people have browsed it

      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);
Copy after login

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

$percentD = 100-$percentA-$percentB-$percentC;
Copy after login

除了这种方法,有其他方法吗?

------解决方案--------------------

$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);
Copy after login

以上就是PHP中计算百分比时怎么保证各部和为1的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!

相关文章:

php 扇形比例百分比显示程序代码

投票最后显示进度条的百分比怎么算

PHP执行进度百分比代码

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template