逻辑运算:我想轻松完成逻辑运算

时间:2015-10-01 01:48:30

标签: c++ logical-operators

我想知道如何减少逻辑运算代码。

 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)

但是如你所知,它不起作用。

如何更改此代码以更轻松地形成?

2 个答案:

答案 0 :(得分:4)

我和@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
  }

还有很多其他方法可以实现这一目标 - 例如,您可以在a中查找set的成员身份(请参阅this answer)。每个人都有自己的好处和适合你的现实世界的问题 - “简单”是一个相对的术语。

答案 1 :(得分:0)

使用数组可能会很好。

#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;
}
相关问题