【问题标题】:How can I round down to the nearest multiple of 3 in PHP? [duplicate]如何在 PHP 中舍入到最接近的 3 倍数? [复制]
【发布时间】:2018-02-25 21:08:13
【问题描述】:

如何使用 PHP 将整数 向下 舍入到最接近的 3 的倍数?并让

例如: 4变成3
10 变成 9
9变成9
8变成6

等等……

【问题讨论】:

    标签: php


    【解决方案1】:

    假设$x 是您的输入:

    print $x-$x%3;
    

    【讨论】:

    • 实际上这会为x=9返回9,因为9 - 9%3 = 9 - 0
    • @Martin 这是错误的,因为?你读过这个问题吗?
    • 我为你读了我的加一:-)
    【解决方案2】:

    这是你要找的吗?

    /**
     * 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
    

    【讨论】:

      【解决方案3】:

      我知道这里有很好的答案,但这个答案是为了更多的选择,使用bcmath

      function floor_to_multiple($number, $multiplier) {
          return bcsub($number, bcmod($number, $multiplier));
      }
      

      【讨论】:

        【解决方案4】:

        如果你想要 3,你可以使用下面的函数:

        function round_nearest_3($value){
            return $value-$value%3;
        }
        

        如果你想为下面的任何值使用函数返回函数:

        function round_nearest_mod($value,$mod){
            return $value-$value%$mod;
        }
        

        示例:

        echo round_nearest_3(4); // becomes 3
        echo round_nearest_3(10); // becomes 9
        echo round_nearest_3(9); // becomes 9
        echo round_nearest_3(8); // becomes 6
        
        echo round_nearest_mod(4,3); // becomes 3
        echo round_nearest_mod(10,3); // becomes 9
        echo round_nearest_mod(9,3); // becomes 9
        echo round_nearest_mod(8,3); // becomes 6
        

        【讨论】:

          【解决方案5】:
          <?php
          //requested number
          $num = 10;
          //calc
          for($i=1;($i*3)<=$num;$i++)$answer[] = $i;
          $answer = max($answer)*3;
          //print result
          print_r($answer);
          

          【讨论】:

          • 这个算法效率很低。
          • 是的,只是一个变体:/
          【解决方案6】:

          我误读了,即使它是完美匹配,也应该向下舍入到 last 前面的增量:

          4 变成 3
          10 变成 9
          9变成6
          8变成6

          因此,如果出于某种原因您需要这个;你的答案是:

          print $x-($x-1)%3-1;
          

          我在理解问题时犯了一个错误,但认为这个答案足够好奇,值得发布。

          【讨论】:

            猜你喜欢
            • 2011-03-16
            • 2021-04-08
            • 1970-01-01
            • 1970-01-01
            • 2011-03-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多