【问题标题】:How can I check if a number is a multiple of the input - PHP如何检查数字是否是输入的倍数 - PHP
【发布时间】:2018-03-06 07:28:13
【问题描述】:

我正在尝试构建一个函数,它接受一个输入数字并检查以下数字是否是该数字的倍数。

function checkIfMult($input,$toBeChecked){
   // some logic
}

示例:

checkIfMult(2,4) // true
checkIfMult(2,6) // true
checkIfMult(2,7) // false

checkIfMult(3,6) // true
checkIfMult(3,9) // true
checkIfMult(3,10) // false

我的第一直觉是使用数组

$tableOf2 = [2,4,6,8,10,12,14,16,18]

但是这样的调用是非常不切实际的:

checkIfMult(6,34234215)

如何检查某项是否是输入的倍数?

【问题讨论】:

    标签: php math multiplication


    【解决方案1】:

    使用% 运算符。

    模运算符将数字相除并返回余数。

    在数学中,倍数意味着余数等于 0。

    function checkIfMult($input,$toBeChecked){
       return $toBeChecked % $input === 0; 
    }
    

    function checkIfMult($input, $toBeChecked){
       console.log('checkIfMult(' + $input +',' + $toBeChecked + ')', $toBeChecked % $input === 0);
       return $toBeChecked % $input === 0;
    }
    
    checkIfMult(2,4) // true
    checkIfMult(2,6) // true
    checkIfMult(2,7) // false
    
    checkIfMult(3,6) // true
    checkIfMult(3,9) // true
    checkIfMult(3,10) // false

    【讨论】:

      【解决方案2】:

      您可以使用取模运算符,如果结果为 0,则该函数应返回 true。模运算符 (%) 执行除法并返回余数。

      http://php.net/manual/en/language.operators.arithmetic.php

      【讨论】:

        【解决方案3】:

        你可以使用%操作符

        function check($a,$b){
           if($b % $a > 0){
             return 0;
           }
           else{
            return 1;
           }
        }
        

        【讨论】:

          【解决方案4】:

          另外,您也可以将 $tobechecked 除以 $input 并使用 floor 函数检查是否有余数。

          if(is_int($result))
           { echo "It is a multiple";
              }
           else
           { echo "It isn't a multiple"; }
          

          【讨论】:

          • 喜欢这个想法,但可以进一步简化。您实际检查的是结果是否为整数。所以if(is_int($result))
          【解决方案5】:

          您可以对% 取模:

          在计算中,modulo 运算求除法后的余数 一个数到另一个数(有时称为模数)。

          function checkIfMult($input,$toBeChecked){
             return !( $toBeChecked % $input );
          }
          

          这跟结果

          echo "<br />" . checkIfMult(2,4); // true
          echo "<br />" . checkIfMult(2,6); // true
          echo "<br />" . checkIfMult(2,7); // false
          
          echo "<br />" . checkIfMult(3,6); // true
          echo "<br />" . checkIfMult(3,9); // true
          echo "<br />" . checkIfMult(3,10); // false
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-04
            • 2013-06-21
            • 1970-01-01
            • 1970-01-01
            • 2021-09-14
            相关资源
            最近更新 更多