php中的整数除法系统问题

我在整数除法脚本中遇到问题。我想要的是,如果我们将 8 分为 3 部分。它应该显示所有四舍五入的数字。比如,3,3,2 如果我们将这 3 相加,结果就是 8。


但以下脚本的划分存在一些差异。它除以 2,2,4。也是 8。但我喜欢上面的 1。请任何人在这种情况下提供帮助。这是代码。


$numbertodivise = 8;

$no = 3;


$intnumber = intval($numbertodivise / $no);

$rem = $numbertodivise % $no;

$array = [];


for($i=1;$i<=$no;$i++) {

    if($i==$no) {

        $array[] = $intnumber + $rem;

    } else {

        $array[] = $intnumber;

    }

}


print_r($array);

它的输出是


Array ( [0] => 2 [1] => 2 [2] => 4 )

请帮我把它做成这样


Array ( [0] => 3 [1] => 3 [2] => 2 )

8不是固定整数。它将是动态的.. 8,9,19,22,88,9888,任何数字都可以。


慕无忌1623718
浏览 82回答 3
3回答

天涯尽头无女友

编辑 将其更改$turn为$noin for 循环。您可以将其用于任何号码。<?php&nbsp; &nbsp; $numbertodivide = 8;&nbsp; &nbsp; $no = 3;&nbsp; &nbsp; $array = [];&nbsp; &nbsp; $added=0;//initialize the variable to track added number to make the given number divisible&nbsp; &nbsp; while($numbertodivide%$no){&nbsp; &nbsp; &nbsp; &nbsp; $numbertodivide+=1;&nbsp; &nbsp; &nbsp; &nbsp; $added++;&nbsp; &nbsp; }&nbsp; &nbsp; $turn=$numbertodivide/$no;//get how many times we have to repeat the divider to get the given number&nbsp; &nbsp; for($i=0;$i<$no-1;$i++){&nbsp; &nbsp; &nbsp; &nbsp; $array[]=$turn;&nbsp; &nbsp; }&nbsp; &nbsp; $array[]=$turn-$added;//trim the added number from the last input of the number.?>

墨色风雨

intval()向下舍入。您想要四舍五入,所以使用ceil().$intnumber = ceil($numbertodivise / $no);$rem = $numbertodivise % $intnumber;$array = array_fill(0, $no, $intnumber);if ($rem != 0) {&nbsp; &nbsp; $array[count($array)-1] = $rem;}

噜噜哒

无需循环。使用您的变量:$count = ceil($numbertodivise / $no);$rem = $numbertodivise - ($no * ($count-1));$array = array_fill(0,$count-1,$no);$array[] = $rem;结果:Array(&nbsp; &nbsp; [0] => 3&nbsp; &nbsp; [1] => 3&nbsp; &nbsp; [2] => 2)
打开App,查看更多内容
随时随地看视频慕课网APP