0

I want to know how to reduce logic operation code.

 int a;

 cin >> a;

 if( a == 1 || a == 3 || a == 5)
    printf("%d", a);

revise the upper code like this

 int a;

 cin >> a;

 if(a == (1 || 3 || 5) )
    printf("%d", a)

But as you know, It doesn't work.

How can I change this code to easier form?

Daniel kim
  • 158
  • 1
  • 11

2 Answers2

3

I'm with @Beta - you already have the simplest form. However, you might find a switch statement provides a more maintainable structure if you add many more "match" values:

int a;

cin >> a;

switch ( a )
{
   case 1:
   case 3:
   case 5:
        printf("%d", a);
        break;
     default:
        // do nothing - not needed, but good habit
  }

There are many other ways to accomplish this - you could look for membership of a in a set, for example (see this answer). Each will have its own benefits and suitability to your real-world problem - "simple" is a relative term.

Community
  • 1
  • 1
Mogsdad
  • 42,835
  • 20
  • 145
  • 262
0

Using an array may be good.

#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;
}
MikeCAT
  • 69,090
  • 10
  • 44
  • 65