For循环会返回多个true语句,如何将其作为一个true bool var

时间:2019-03-26 03:05:58

标签: c++ return boolean

我有一个for循环,它遍历整数向量以找到特定的一位数字(6)和一个十位数(1或2)。如果向量的所有整数都为真,则应返回true,如果只有一个为false,则应返回false并打印使该元素为false的元素。

在这种情况下,向量中的整数满足条件。但是我不知道如何将三个true编译成一个可返回的true

//    ∀x∈D,if the ones digit of x is 6, then the tens digit is 1 or 2.
// vector contains [-48, -14, -8, 0, 1, 3, 16, 23, 26, 32, 36]

void question5 (std::vector<int> x){

    int num;
    int digit1;
    int digit2;

    for (int i=0; i <x.size();i++){
        num = x.at(i); //stores the integer from the vector at position i
        digit1 = num % 10; // the ones digit is stored into digit1

        if (digit1 == 6){ // checks to see if the ones digit is 6
            digit2 = num/10; // if true gets the tens digit in num
            if ((digit1 ==6 && (digit2 == 1||2)))
                std::cout << "True"<< std:: endl;
            else
                std::cout << "False"<< std::endl;
        }

    }  
}

2 个答案:

答案 0 :(得分:0)

  

但是我不知道如何将三个true编译成一个可返回的true

  1. 将函数的返回类型更改为bool
  2. 在第一个符号上返回false
  3. 如果您从未遇到过false条件,请最后返回true
  4. 确保条件使用正确。 digit2 == 1||2不正确。

for (int i=0; i <x.size();i++){
    num = x.at(i); //stores the integer from the vector at position i
    digit1 = num % 10; // the ones digit is stored into digit1

    if (digit1 == 6){ // checks to see if the ones digit is 6
        digit2 = num/10; // if true gets the tens digit in num

        // No need for digit == 6 again. It's already been tested.
        // The correct way to test whether digit2 is 1 or 2.
        if ( (digit2 == 1) || (digit2 == 2) )
        {
            std::cout << "True"<< std:: endl;
        }
        else
        {
            std::cout << "False"<< std::endl;
            return false;
        }
    }
}  

return true;

一个更简单的测试是计算num % 100并针对1626测试结果。

for (int i=0; i <x.size();i++){
    num = x.at(i);
    int num2 = num % 100;
    if ( num2 == 16 || num2 == 26 )
    {
        std::cout << "True"<< std:: endl;
    }
    else
    {
        std::cout << "False"<< std::endl;
        return false;
    }
}

return true;

答案 1 :(得分:0)

将三个条件编译成一个语句可以使用由“ and”或“ &&”连接的三个条件来完成。如果同时出现这三种情况,则系统将发生故障,如下所示。在检查完所有向量之后,就可以成功了。

我认为负数的问题含糊不清。按照书面规定,我相信-36作为第一个数字会通过测试,但前提是您要注意负号:

#include <iostream>
#include <vector>

//    ∀x∈D,if the ones digit of x is 6, then the tens digit is 1 or 2.
// vector contains [-48, -14, -8, 0, 1, 3, 16, 23, 26, 32, 36]

void question5(std::vector<int> x)
{
  int i = 1;
  for (auto &number: x) {
    int abs_number = abs(number);
    if (abs(abs_number) % 10 == 6 and (abs_number / 10 != 1 and abs_number / 10 != 2)) {
      std::cout << "Element #" << i << " with a value of " << number
                << " is the first failing element." << std::endl;
      return;
    }
    i++;
  }
  std::cout << "All elements satisfy the criteria." << std::endl;
  return;
}

int main()
{
  std::vector<int> vect{-48, -14, -8, 0, 1, 3, 16, 23, 26, 32, 36};

  question5(vect);
  return 0;
}