Multiple conditions in an if clause

后端 未结 9 1067
醉梦人生
醉梦人生 2021-02-02 06:44

If I have an if statement that needs to meet these requirements:

if(cave > 0 && training > 0 && mobility > 0 && sleep > 0)
         


        
9条回答
  •  旧巷少年郎
    2021-02-02 07:29

    Assuming 32-bit ints.

    if ((cave | training | mobility | sleep) > 0)
    

    If any of the above numbers are negative, the result of the OR will be negative and the requirements aren't met.

    Edit: that's equivalent to if(cave >= 0 && training >= 0 && mobility >= 0 && sleep >= 0) and won't when some of the parameters are 0. The fix is to invert the sign bit:

    if ((~cave | ~training | ~mobility | ~sleep) <= 0)
    

    Some alternative ways which work even for floating-point values

    if (cave*training*mobility*sleep > 0)
    if (Math.sign(cave) * Math.sign(training) * Math.sign(mobility) * Math.sign(sleep) > 0)
    if (Math.sign(cave) | Math.sign(training) | Math.sign(mobility) | Math.sign(sleep) > 0)
    

提交回复
热议问题