doudong4532 2018-03-06 07:28
浏览 987
已采纳

如何检查数字是否是输入的倍数 - PHP

What I am trying to build is a function that takes an input number and checks if the following number is a multiple of that number.

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

example:

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

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

My first instinct was to use arrays

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

But then a call like this would be highly unpractical:

checkIfMult(6,34234215)

How can I check to see if something is a multiple of the input?

  • 写回答

5条回答 默认 最新

  • dsa88885555 2018-03-06 07:30
    关注

    Use the % operator.

    The Modulo operator divides the numbers and returns the remainder.

    In math, a multiple means that the remainder equals 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

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!