开发者

php round/ceil/floor how to make a number to Multiples of 7

开发者 https://www.devze.com 2023-04-10 03:22 出处:网络
Firstly poor of my mathematica. I tried to use php to make a number to Multiples of 7. the rules as below:

Firstly poor of my mathematica. I tried to use php to make a number to Multiples of 7. the rules as below:

$num >=0;

$num = '0'; => output '7'    
$num = '1'; => output '7'
$num = '6'; => output '7'
$num = '8'; => output '14'
$num = '14'; => output '14'
$num = '16'; => output '21'
$num = '20'; => output '21'
$num = '40'; => output '42'
$num = '84'; => output开发者_如何学Python '84'
...

I cost many times, but I am not smart to solve this by myself. such as

 echo round(($num*7-1)/7); // not a right answer.

any one is kindly help me? Thanks.


Your requirements are not consistent if the output for 0 is 7; 0 is already a multiple of 7, since 0 * 7 = 0.

echo ceil($num / 7) * 7;

Alternatively, use the modulus operator:

$m = $num % 7;
echo $m == 0 ? $num : $num - $m + 7;


Try ceil($num / 7) * 7. The code:

<?php

for ($i = 0; $i < 50; $i++) {
  echo get_number($i) . "\n";
}

function get_number($num) {
  return ceil($num / 7) * 7;
}

?>

Produces:

0 => 0
1 => 7
2 => 7
3 => 7
4 => 7
5 => 7
6 => 7
7 => 7
8 => 14
9 => 14
10 => 14
11 => 14
12 => 14
13 => 14
14 => 14
15 => 21
...
46 => 49
47 => 49
48 => 49
49 => 49


One possibility is to use modulo arithmetic, e.g.:

$x = $whatever;
while($x % 7 != 0){
   $x++
}

echo $x; // will now be next multipe of seven >= $whatever
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号