【问题标题】:Logic Operations : I want to make Logic operations easily逻辑运算:我想轻松地进行逻辑运算
【发布时间】:2015-12-28 22:57:17
【问题描述】:
我想知道如何减少逻辑操作代码。
int a;
cin >> a;
if( a == 1 || a == 3 || a == 5)
printf("%d", a);
像这样修改上面的代码
int a;
cin >> a;
if(a == (1 || 3 || 5) )
printf("%d", a)
但如你所知,它不起作用。
如何将此代码更改为更简单的形式?
【问题讨论】:
标签:
c++
logical-operators
【解决方案1】:
我支持@Beta - 你已经有了最简单的形式。但是,如果添加更多“匹配”值,您可能会发现 switch 语句提供了更易于维护的结构:
int a;
cin >> a;
switch ( a )
{
case 1:
case 3:
case 5:
printf("%d", a);
break;
default:
// do nothing - not needed, but good habit
}
还有许多其他方法可以实现这一点 - 例如,您可以在 set 中查找 a 的成员资格(参见 this answer)。每个都有自己的优点和适用于您的实际问题 - “简单”是一个相对术语。
【解决方案2】:
使用数组可能会很好。
#include <cstdio>
#include <iostream>
using std::cin;
int main(void){
int a;
cin >> a;
{
static const int to_match[3] = {1, 3, 5};
bool yes = false;
for (size_t i = 0; i < sizeof(to_match) / sizeof(to_match[0]); i++) {
if (a == to_match[i]) {yes = true; break;}
}
if(yes)
printf("%d", a);
}
return 0;
}