there have two value, $a
and $b
. I need make a judge, $a
is not 3 times as bigger as b or $b
is not 3 times as bigger as $a
, echo $a.' and '.$b;
else not.
for explain:
if $a
= 5, $b
=1 so $b
*3 = 3, $b
*3 < $a
, then echo 'nothing';
if $a
= 5, $b
=2 so $b
*3 = 6, $b
*3 > $a
, then echo $a.' and '.$b;//5 and 6
if $b
= 5, $a
=1 so $a
*3 = 3, $a
*3 < $b
, then echo 'nothing';
if $b
= 5, $a
=2 so $a
*3 = 6, $a
*3 > $b
, then echo $a.' and '.$b;//6 and 5
one of my code:
$a='5';
$b='1';
if ((!($a>=($b*3))) or (!($b>=($a*3)))){
echo 开发者_如何学Python$a.' and '.$b; //this may be echo 'nothing'
}else{
echo 'nothing';
}
Replace $a[0]
, $a[1]
, $b[0]
, and $b[1]
with $a
, $a
, $b
, and $b
, respectively.
From your examples, you seem to want to print 'nothing' if the values are very different, but if the values are close (within a factor of 3) then you print the values.
You just need to fix the logic in your test line:
if ($a < $b * 3 && $b < $a * 3) {
is this what you are asking?
function checkAandB($a, $b)
{
if($a==0 || $b==0)
return true;
else if ($a/$b>=3 || $b/$a>=3)
return true;
else
return false
}
//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.' and '.$b;//6 and 5
if ($b > $a) && ($b < $a*3) { echo $a . ' and ' . $b; }
What if $a==$b?
I would make it much simpler than that. I like to always follow KISS. If a person needs more than 5 seconds to read and to understand my line I would scrap it.
I would make a quick check which is smaller or bigger, then check if they are 3 times bigger or not.Maybe not as "efficient" as yours. but 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
It's pseudocode :) converted to your suitable language.
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
精彩评论