php比较值,如果没有

时间:2011-04-13 21:02:46

标签: php

有两个值,$a$b。我需要做一个判断,$a不是b的3倍,或$b不是$a的3倍,echo $a.' and '.$b;不是。

解释:

如果$a = 5,$b = 1,那么$b * 3 = 3,$b * 3< $a,然后回声“没有”;

如果$a = 5,则$b = 2,$b * 3 = 6,$b * 3> $a,然后回显$a.' and '.$b;//5 and 6

如果$b = 5,$a = 1,那么$a * 3 = 3,$a * 3< $b,然后回声“没有”;

如果$b = 5,则$a = 2,$a * 3 = 6,$a * 3> $b,然后回显$a.' and '.$b;//6 and 5

我的一个代码:

$a='5';
$b='1';
if ((!($a>=($b*3))) or (!($b>=($a*3)))){
    echo $a.' and '.$b; //this may be echo 'nothing'
}else{
  echo 'nothing';
}

6 个答案:

答案 0 :(得分:3)

$a[0]$a[1]$b[0]$b[1]替换为$a$a$b和{{ 1}},分别。

答案 1 :(得分:1)

这就是你问的问题吗?

function checkAandB($ a,$ b) {
if($ a == 0 || $ b == 0)
返回true; 否则if($ a / $ b> = 3 || $ b / $ a> = 3) 返回true; 其他 返回false }

答案 2 :(得分:1)

从您的示例中,如果值非常不同,您似乎希望打印“无”,但如果值接近(在3倍之内),则打印值。

您只需修改测试行中的逻辑:

if($ a< $ b * 3&& $ b< $ a * 3){

答案 3 :(得分:1)

//if $a = 5, $b=1 so $b*3 = 3, is still smaller than $a, then echo 'nothing';
if ($a > $b) && ($a > $b*3) { echo 'nothing'; }

//if $a = 5, $b=2 so $b*3 = 6, is bigger than $a, then echo $a.' and '.$b;//5 and 6
if ($a > $b) && ($a < $b*3) { echo $a . ' and ' . $b; }

//if $b = 5, $a=1 so $a*3 = 3, is still smaller than $b, then echo 'nothing';
if ($b > $a) && ($b > $a*3) { echo 'nothing'; }

//if $b = 5, $a=2 so $a*3 = 6, is bigger than $b, then echo $a.'&nbsp;and&nbsp;'.$b;//6 and 5
if ($b > $a) && ($b < $a*3) { echo $a . ' and ' . $b; }

如果$ a == $ b?

怎么办?

答案 4 :(得分:1)

我会比这简单得多。我喜欢永远跟随KISS。 如果一个人需要超过5秒的时间阅读并理解我的行,我会废弃它。

我会快速检查哪个更小或更大,然后检查它们是否大3倍。也许不像你的那样“高效”。但是meh :)。

function checkAandB($a,$b){
    if $a >= $b             //I assumed that if equal then it doesn't matter
         $smaller = $b;
         $bigger = $a
     else
         $smaller = $a;     //fixed a typo in here
         $bigger = $b;
    if $smaller < (3 * $bigger )
         do nothing
    else 
        echo $a and $b

它是伪代码:)转换为您合适的语言。

答案 5 :(得分:0)

function compareAB($a, $b) {
  return ($a < ($b * 3)) && ($b < ($a * 3)) ? "$a and $b" : "nothing";
  }

echo compareAB(5,1); // nothing
echo compareAB(5,2); // 5 and 2