简体   繁体   English

多条件循环

[英]Do-While Loop with Multiple Conditions

Can a do-while loop have multiple conditions? do-while循环可以有多个条件吗? If so, I can't figure out why the code below is failing on all but the first condition. 如果是这样,我无法弄清楚为什么下面的代码除了第一个条件之外,其他所有条件都失败。

Functions used... 使用的功能...

function gcf($a,$b) {
$a = abs($a); $b = abs($b);
if( $a < $b) list($b,$a) = Array($a,$b);
if( $b == 0) return $a;
$r = $a % $b;
while($r > 0) {
    $a = $b;
    $b = $r;
    $r = $a % $b;
}
return $b;
}


function factors($n){
$factors_array = array();
for ($x = 1; $x <= sqrt(abs($n)); $x++)
{
    if ($n % $x == 0)
    {
        $z = $n/$x; 
        array_push($factors_array, $x, $z);
    }
}
return $factors_array;
}

Code... 码...

$a = $b;

do{
    $a = mt_rand(8, 100);
    $a_factors_array = factors($a);

    $b = mt_rand(8, 100);
    $b_factors_array = factors($b);

} while ($a == $b && count($a_factors_array) < 4 && count($b_factors_array) < 4 && gcf($a, $b) == 1);

echo $a . '<br>';
echo $b . '<br>';

echo count($a_factors_array) . '<br>';
echo count($b_factors_array) . '<br>';

echo gcf($a, $b) . '<br>';

I keep getting numbers for $a and $b that have less than 4 factors and have a GCF of 1. Any ideas? 我不断获得$ a和$ b小于4且GCF为1的数字。有什么想法吗?

You'll need || 您需要|| instead of && . 代替&& You want to repeat the loop as long as any one of your conditions is met. 只要您满足任何条件,就想重复循环。 Currently the loop is only repeated if all of the conditions are met. 当前,仅在满足所有条件时才重复循环。

I think you have an ANDs where you meant an ORs: 我认为您有一个AND,意思是一个OR:

do{
    $a = mt_rand(8, 100);
    $a_factors_array = factors($a);

    $b = mt_rand(8, 100);
    $b_factors_array = factors($b);

} while ($a == $b || count($a_factors_array) < 4 || count($b_factors_array) < 4 || gcf($a, $b) == 1);

With your way, the while stops if $a !== $b which is probably not what you want. 用自己的方式,如果$a !== $b$a !== $b while停止,这可能不是您想要的。

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

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