我的脚本中有以下简单的除法计算:
<?php
$total = 1001;
$people = 5;
$division= $total / $people;
echo "division = ".$division;
?>
这会输出division = 200.2
。
是否可以将其存储起来,如下所示?
$division[0] = 200;
$division[1] = 200;
$division[2] = 200;
$division[3] = 200;
$division[4] = 201;
答案 0 :(得分:2)
// initital conditions
$total = 1001;
$people = 5;
// count what is the minimal value, that all the results will have
$value = floor($total / $people);
$result = array_fill(0, $people, $value);
// distribute missing "+1"s as needed in the result
$overheads = $total - $value * $people;
for ($i = 0; $i < $overheads; $i++)
$result[$i]++;
// voila...
var_dump($result);
答案 1 :(得分:2)
试试这个:
$total = 1001;
$people = 5;
$division = array();
$extra = $total % $people; // Stores the extra number i.e 1
$i = 1;
while ($i <= $people) {
/* For the last array element, add the extra number */
if ($i == $people) {
$division[] = floor($total/$people) + $extra;
} else {
$division[] = floor($total/$people);
}
$i++;
}
答案 2 :(得分:1)
试试这个,
$total = 1001;
$people = 5;
$division = [];
$difference = intval($total%100);
for($i =0 ; $i < $people; $i++){
$division[] = ($i == $people - 1) ? (intval($total/ $people) + $difference) : intval($total/ $people);
}
print_r($division);
die;
答案 3 :(得分:1)
<?php
$total = 1001;
$people = 5;
$division = array();
$division[] = round($total / $people);
echo "division = ".$division[0];
?>
此数组对象将为您提供从数组中存储和检索的值。