php 如果一个数字是从不同数字开始的 3 的倍数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16622941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:27:24  来源:igfitidea点击:

If a number is multiple of 3 starting at different numbers

phpmath

提问by Fisu

I'm not sure of the mathematical term for what I'm after, but I'm looking for a way in PHP to assign a variable to an integer which is a multiple of three. The multiple will start from numbers 1, 2 and 3. All integers will fall under one of three variables $varA, $varBand $varC. I think the modulus operator should be used, but I'm not sure how.

我不确定我所追求的数学术语,但我正在寻找一种在 PHP 中将变量分配给一个整数的方法,该整数是三的倍数。倍数将从数字 1、2 和 3 开始。所有整数都属于三个变量$varA,$varB和 之一$varC。我认为应该使用模数运算符,但我不确定如何使用。

$varAcould include numbers 1, 4, 7, 10, 13, 16, 19 etc.
$varBcould include numbers 2, 5, 8, 11, 14, 17, 20 etc.
$varCcould include numbers 3, 6, 9, 12, 15, 18, 21 etc.

$varA可包括数字 1、4、7、10、13、16、19 等
$varB可包括数字 2、5、8、11、14、17、20 等
$varC可包括数字 3、6、9、12、15、18 , 21 等

I want to assign the number from an if statement, such as:

我想从 if 语句中分配数字,例如:

if( $number == (test for $varA) ) {
    $number = $varA
} else if( $number == (test for $varB) ) {
    $number = $varB
} else {
    $number = $varC
}

回答by David M

Yes, you need the modulo (not modulus) operator. This gives the remainder when divided by three - either 0, 1 or 2.

是的,您需要模(不是模)运算符。这给出了除以 3 的余数 - 0、1 或 2。

The first test would be:

第一个测试是:

if ($number % 3 == 1)

You may wish to evaluate only once and use in a switch statement - as the other David comments below, this is marginally more efficient:

您可能希望只计算一次并在 switch 语句中使用 - 正如下面的其他大卫评论的那样,这稍微更有效:

switch ($number % 3) {
    case 1:
        $number = $varA;
        break;
    case 2:
        $number = $varB;
        break;
    case 0:
        $number = $varC;
        break;
}