How to write several conditions if

I have two variables Aand B, and I want to write code where, if one of the two variables is equal

151 or 156 or 720

and the other is not equal to one of these numbers, then the third variable C = 0is equal to one.

So for example

1) if A = 151 and B = 700 then C = 1 
2) if A = 151 and B = 720 then C = 0
3) if A = 140 and B = 700 then C = 0

This is the code

int A = 0
cin >> A;
int B = 0
cin >> B;
int C=0;
int DECKlist[3] = {151,156,720}
for(int d=0; d<3;d++){
      if(A== DECKlist[d]){
           for(int w=0; w<3;w++){
                if(B==DECKlist[w]) C=0;
                 else C=1;
            }
       }
       if(B== DECKlist[d]){
           for(int w=0; w<3;w++){
                if(A==DECKlist[w]) C=0;
                 else C=1;
            }
       }
}

This is normal? Are there other ways to do this?

+4
source share
4 answers

This is an exclusive OR, XOR. There is no logical XOR in C ++, but you can use the bit-XOR for your case and use the fact that the result of the logical operator is boolthat will be displayed in 0 or 1:

#include <iostream>

int main()
{
    int A, B, C;

    std::cin >> A;
    std::cin >> B;

    A = (A == 151 || A == 156 || A == 720);
    B = (B == 151 || B == 156 || B == 720);

    C = A ^ B;

    std::cout << C << std::endl;
}

, , . , , a, well, std::set.

+5

. , std::binary_search XOR, DECKlist

#include <algorithm>
#include <iterator>

//...

int DECKlist[] = { 151, 156, 720 };

//...

if ( std::binary_search( std::begin( DECKlist ), std::end( DECKlist ), A ) ^
     std::binary_search( std::begin( DECKlist ), std::end( DECKlist ), B ) )
{
   C = 1;
}

, . " " quntity.:)

+2

int c=0;
for(int i=0; i<3; i++){
    if(A == DECKlist[i]) c++;
    if(B == DECKlist[i]) c++;
}
c = c%2;

, , , 2.

+1

, , . ++, ( ), . ++ 11: std::begin std::end auto :

#include <algorithm>
#include <utility>
#include <iterator>

template<class Array, class T>
bool find_in( Array const& arr, T const& t ) {
  using std::begin; using std::end;
  const auto b = begin(arr);
  const auto e = end(arr);
  const auto it = std::find( b, e, t ); // search the range for t
  return !(e != it);
}

find_in , true, .

. using namespace std;, - std:: .

#include <iostream>

int main() {
  int A = 0
  std::cin >> A;
  int B = 0
  std::cin >> B;
  int C=0;
  int DECKlist[3] = {151,156,720};
  bool A_in_list = find_in(DECKlist, A);
  bool B_in_list = find_in(DECKlist, B);
  if (A_in_list != B_in_list)
    C = 1;
  std::cout << C << "\n";
}

, , "" .

, - , , !=.

0
source

All Articles