多条件循环 [英] Do-While Loop with Multiple Conditions

查看:96
本文介绍了多条件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

do-while循环可以有多个条件吗?如果是这样,我无法弄清楚为什么下面的代码除了第一个条件之外,在所有条件下都失败。

Can a do-while loop have multiple conditions? If so, I can't figure out why the code below is failing on all but the first condition.

使用的函数...

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;
}

代码...

$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>';

我不断得到$ a和$ b的因子小于4且GCF为1.有什么想法吗?

I keep getting numbers for $a and $b that have less than 4 factors and have a GCF of 1. Any ideas?

推荐答案

您将需要 || & 。只要满足您的条件之一,您就想重复循环。当前,仅在满足 all 个条件的情况下重复循环。

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.

这篇关于多条件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆