简体   繁体   English

如何在 JavaScript 中实现以下条件:

[英]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 :例如,我们房间里有 9 只宠物:猫、猴子和兔子,如何检查猫与猴子和兔子的相关性,不大于 1:2 ?....true 值应为 2 - 1,或2 - 4 和 falsy 1 - 3,或 2 - 5......下面是我试图解决这个任务的方法:

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.如果我理解您的问题,如果猫的数量除以(猴子 + 兔子)的数量大于 1/2,您想返回 false。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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