php round / ceil / floor如何将数字设为7的倍数

时间:2011-10-03 22:34:16

标签: php

首先我的mathematica很差。我试图使用php将数字设为7的倍数。规则如下:

$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 '84'
...

我花了很多倍,但我自己解决这个问题并不聪明。比如

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

任何人都善意帮助我?感谢。

3 个答案:

答案 0 :(得分:7)

如果0的输出为7,则您的要求不一致; 0已经是7的倍数,因为0 * 7 = 0。

echo ceil($num / 7) * 7;

或者,使用模数运算符:

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

答案 1 :(得分:3)

试试ceil($num / 7) * 7。代码:

<?php

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

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

?>

产地:

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

答案 2 :(得分:2)

一种可能性是使用模运算,例如:

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

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