有没有更好的方法来检查这两个变量而不是四个ifs?

必须有两个变量,例如 A 和 B,这两个将取值 0 0、0 1、1 0 或 1 1。我需要检查这两个变量并返回 0 到 3 之间的值,有没有更好的比做四个if语句更像这样的方法:

if(B == 0 && A == 0){
  return 0;
}
if(B == 0 && A == 1){
  return 1;
}
if(B == 1 && A == 0){
  return 2;
}
if(B ==1 && A == 1){
  return 3;
}

回答

您显示的四个条件可以用单行解决:

return A + B * 2;

也就是说,当然,如果AandB永远不会0or以外的任何值1

  • For identical behavior to the original code, you could use `if ((A|B|1) == 1) return A + B * 2;` -- only return if both A and B are 0 or 1; fall through if either has any other value.
  • Simple math > tons of `if` statements.
  • This has two operators so it's basically multivariable calculus, but I'll allow it!
  • personally, I prefer the `(B << 1) | A` route, since we're basically just mashing binary values together here.
  • @ChristianGibbons Yeah - I considered a *similar* bitwise/logical solution but decided that old-fashioned maths was probably simpler in terms of understanding.

以上是有没有更好的方法来检查这两个变量而不是四个ifs?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>