Elegantly determine if more than one boolean is “true”

前端 未结 22 1107
深忆病人
深忆病人 2020-12-04 13:40

I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would al

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 14:29

    if you mean more than or equal to one boolean equals to true, you could do it like

    if (bool1 || bool2 || bool3 || bool4 || bool5)
    

    If you need more than one (2 and above) booleans equal to true, you can try

    int counter = 0;
    if (bool1) counter++;
    if (bool2) counter++;
    if (bool3) counter++;
    if (bool4) counter++;
    if (bool5) counter++;
    if (counter >= 2) //More than 1 boolean is true
    

提交回复
热议问题