简体   繁体   中英

How to realize the following condition in JavaScript:

For example, we have 9 pets in the room: cats, monkeys, and rabbits, how to check that correlation of cats to monkeys and rabbits, not bigger than 1:2 ?....truthy value would be 2 - 1, or 2 - 4 and falsy 1 - 3, or 2 - 5......Below is how I tried to solve this task :

function petsInRoom(cats, monkeys, rabbits) {
  // write code here
  if ((monkeys + rabbits) / cats != 2) {
    return false;
  } else {
    return true;
  }
};

If I understand your question, you want to return false if the number of cats divided by the number of (monkeys + rabbits) if superior to 1/2.

your should write something like this:

if (cats / (monkeys + rabbits) > 1/2) {
  return false;
} else {
  return true;
}

or you can write it in one line:

return !( cats / (monkeys + rabbits) > 1/2);

Edit: something like this should work just fine:

function petsInRoom(cats, monkeys, rabbits) {
  if (rabbits === undefined) rabbits = 0;
  if ( cats / (monkeys + rabbits) > 0.5) {
    return false;
  } else {
    return true;
  }
};

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