【发布时间】:2019-08-16 08:54:40
【问题描述】:
我有一个 for 循环,它通过一个整数向量来找到一个特定的数字(6)和一个十位数字(1 或 2)。如果向量的所有整数都为真,我应该返回真,如果只有一个为假,我应该返回假并打印使其为假的元素。
在这种情况下,向量中的整数满足条件。但我不知道如何将三个 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;
}
}
}
【问题讨论】:
-
std::all_of() 在这里会很有用,而不是循环。您是否了解标准算法或如何使用 lambda?
-
感谢您提出问题。请包含一个 main() 函数并提供一个Compilable, Minimal, Complete, and Verifiable Example。这有助于我们帮助您。如果您可以在仍然创建故障的同时使您的问题尽可能简单,它将帮助我们隔离使您的代码正常工作的问题。通过提供一个 main() 函数,它可以为试图复制您的错误并为您提供帮助的人节省时间。
-
您实际上并没有返回任何真实的陈述。您只需输出字符串“True”。为什么不只是一个布尔变量开始为假,一旦你将它设置为真,就打破循环。如果这太难了,那么计数器匹配了多少条件。如果 > 0,则打印“True”。