如何使用PHP将整数向下舍入到最接近的3的倍数?并且< 3为0。
例如:
4变为3
10变为9
9变为9
8变为6
等等......
答案 0 :(得分:4)
假设$x
是您的输入:
print $x-$x%3;
答案 1 :(得分:1)
这就是你要找的。 p>
/**
* Round an integer down to the nearest multiple of the given multiple
* @param integer $number
* @param integer $multiple
* @return integer
*/
function round_down_to_multiple_of( int $number, int $multiple = 3 ): int
{
return (int)($multiple * floor( $number/$multiple ));
}
# TESTS
$numbers = [ 10, 9, 8, 1, 0 ];
foreach( $numbers as $number ){
printf( '%d became %d'.PHP_EOL, $number, round_down_to_multiple_of( $number, 3 ) );
}
运行上述测试后,我得到以下结果:
10 became 9
9 became 9
8 became 6
1 became 0
0 became 0
答案 2 :(得分:0)
我误读了即使它是完美契合,它应该向下舍入到 last 之前的增量:
4变为3
10变为9
9变为6
8变为6
因此,如果由于某种原因你需要这个;你的答案是:
print $x-($x-1)%3-1;
我在理解这个问题时犯了一个错误,但认为这个答案非常好奇,值得发帖。