如果条件如何写多个

时间:2014-11-05 14:27:29

标签: c++

我有两个变量AB,我想编写一个代码,如果两个变量中的一个等于

151 or 156 or 720

而另一个不等于这些数字之一,则第三个变量C = 0等于一。

所以例如

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

这是代码

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;
            }
       }
}

这样好吗?还有其他更好的方法吗?

4 个答案:

答案 0 :(得分:5)

这是异或,异或。 C ++中没有逻辑XOR,但是你可以在你的情况下使用逐位XOR,并利用逻辑运算符的结果为bool的事实,它将映射到0或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;
}

我在这里使用了一个简单的表达式来检查一个数字是否是三个提供的数字之一。对于要检查的较大数字集,您可以使用,std::set

答案 1 :(得分:2)

您可以使用标准算法。例如,您可以使用标准algoritnm 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;
}

在这种情况下,您可以在数组中添加新值,该方法将照常正常工作。它不依赖于&#34;魔术数字&#34;和他们的实力。:))

答案 2 :(得分:1)

怎么样

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

基本上,计算匹配数,如果是2,则将其设为零。

答案 3 :(得分:0)

我要做的第一件事就是隐藏搜索代码。这里有一些C ++,它会线性搜索一个数组(或任何其他容器),如果有给定值的话。它使用两个C ++ 11功能:std::beginstd::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";
}

搜索代码,因为我把它放在辅助函数中,在&#34;核心&#34;中非常干净。该计划的逻辑。

我们想知道一个人在列表中,而不是另一个,我们只是使用!=来比较结果。