简体   繁体   English

else if 怎么写成逻辑语句?

[英]How to write else if as logical statement?

I want to write an if-else statement as a logical statement.我想写一个 if-else 语句作为逻辑语句。 I know that:我知道:

if (statement1){
   b=c
}
else{
   b=d
}

can be written as:可以写成:

b=(statement1 && c)||(!statement1 && d)

But how do I write the following if-else statements as logical?:但是如何将以下 if-else 语句编写为合乎逻辑的?:

if (statement1){
   b=c
}
else if (statement2){
   b=d
}
else{
   b=e
}

I have thought of something like:我想到了类似的东西:

b=(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)

I'm sorry if there is already a post about this.如果已经有关于此的帖子,我很抱歉。 I have tried, but couldn't find anything similar to my problem.我已经尝试过,但找不到与我的问题类似的任何东西。

As with all logical statement building, it'll be easiest to create a truth table here.与所有逻辑语句构建一样,在这里创建真值表是最容易的。 You'll end up with:你最终会得到:

+--+--+--------+
|s2|s1| result |
+--+--+--------+
| 0| 0|   e    |
+--+--+--------+
| 0| 1|   c    |
+--+--+--------+
| 1| 0|   d    |
+--+--+--------+
| 1| 1|   c    |
+--+--+--------+

So un-simplified, that'll be如此简单,那将是

(!s1 & !s2 & e) || (!s2 & s1 & c) || (s2 & !s1 & d) || (s1 & s2 & c)

This can be simplified by combining the two c results and removing the s2 :这可以通过组合两个c结果并删除s2来简化:

(!s1 & !s2 & e) || (s2 & !s1 & d) || (s1 & c)

(note that this will be faster in C++ and match the if statements closer with s1 & c as the first term. This will especially make a difference if evaluating any of these values will cause outside effects) (请注意,这在 C++ 中会更快,并将if语句与s1 & c作为第一项更接近。如果评估这些值中的任何一个会导致外部影响,这将特别重要)


Note that what you built,请注意,您构建的内容,

(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)

will function incorrectly if statement1 is true, c is false, and both statement2 and d are true (you'll get a result of true when you should have false).如果statement1为真, c为假,并且statement2d都为真,则 function 将不正确(当你应该为假时,你会得到真的结果)。

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

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