简体   繁体   English

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

[英]How can I check if a number is a multiple of the input - 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? 如何检查输入是否是输入的倍数?

Use the % operator. 使用运算符。

The Modulo operator divides the numbers and returns the remainder. 模运算符将数字相除并返回余数。

In math, a multiple means that the remainder equals 0. 在数学上,倍数表示余数等于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 

You can use the modulus operator, if the result is 0 then the function should return true. 您可以使用模运算符,如果结果为0,则该函数应返回true。 The modulus operator ( % ) performs a division and returns the remainder. 模运算符( )执行除法并返回余数。

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

Alternatively, You can also divide the $tobechecked by $input and check if there is a remainder by using the floor function. 或者,您也可以将$ tobechecked的$除以$ input并使用floor函数检查是否有余数。

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

You can modulo % Like: 您可以对%求模,例如:

In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus). 在计算中, modulo运算将一个数除以另一个后的余数(有时称为模数)。

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

This follow the result 这遵循结果

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

You can use % operator 您可以使用%运算符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM