简体   繁体   中英

what is wrong with this if-statement

I have absolutely no idea what is wrong with this if statement, when I sent values lon = -3 and lat = 7 it should return false but it doesn't.

  if (b < 0 && ((lon > 8 && lon < 0) || (lat > 8 && lat < 0)))
  {

    return false;
  }
  else
  {
    return true ;
  }

decomposing each value...

int lon = -3;
int lat = 7;

  if (b < 0 && // i don't know b value
            ((-3 > 8 && //false
            -3 < 0)     //true
     || (7 > 8 && //false
     7 < 0 //false
     ))) 
  {

    return false;
  }
  else
  {
    return true ;
  }

it results in int lon = -3; int lat = 7;

  if (b < 0 && // i don't know b value
            (false || false)) 
  {

    return false;
  }
  else
  {
    return true ;
  }

and finally is:

  if (false) 
  {

    return false;
  }
  else
  {
    return true ;
  }

then it return true!

Though the logic flawed with this if statement, maybe there is still something to be learned here. Instead of evaluating the if statement and then returning either true or false , you could clean that up a bit and just do something like:

return b < 0 && ((lon > 8 && lon < 0) || (lat > 8 && lat < 0))

But back to the logical error, perhaps your understanding of how the inequality operators work. It would make more sense if you did something like lon > 0 && lon < 8 which would read as longitude is greater than zero and less than eight .

If i am reading your statement correct you will never ever get false. To get false lon must me less than zero AND more than 8 ... that is not possible. The same case with lat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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