我正在努力完成这个if语句.必须有一种更简单的方法来完成所有组合,因为这不是一个好的做法.
if( one == true && two == true && three == true ...)
else if( one != true && two == true && three == true ...)
Run Code Online (Sandbox Code Playgroud)
我想知道我是否想要通过所有组合有没有其他方式这样做而不是复制表达式?
das*_*ght 19
一种方法是将您的one,, two和three值转换为int具有正确设置的位的单个,并使用switch二进制掩码上的语句,如下所示:
int combined=0;
// Construct a binary representation using your Boolean values as bits:
// Value of one goes to bit zero
if (one) combined |= (1 << 0);
// Value of one goes to bit one
if (two) combined |= (1 << 1);
// Value of three goes to bit two
if (three) combined |= (1 << 2);
switch (combined) {
case 0: // All false
break;
case 1: // one is true, other are all false
break;
...
case 7: // All true
break;
}
Run Code Online (Sandbox Code Playgroud)
所有八种组合现在都编码为整数值:
int three two one
_-- ----- --- ---
0 - 0 0 0
1 - 0 0 1
2 - 0 1 0
3 - 0 1 1
4 - 1 0 0
5 - 1 0 1
6 - 1 1 0
7 - 1 1 1
Run Code Online (Sandbox Code Playgroud)
毫无疑问,对于没有记忆小数字二进制表示的代码的读者,你需要大量注释这样的代码.
Mar*_*ell 18
你可以这样做:
int i = (one ? 1 : 0) | (two ? 2 : 0) | (three ? 4 : 0);
switch(i)
{
case 0:
// ...
case 1:
// ...
case 7:
// ...
}
Run Code Online (Sandbox Code Playgroud)
这将是非常快的-这将是一个直接跳转(该switch操作码),并表达将只每一次评估.