【发布时间】:2017-10-21 02:43:36
【问题描述】:
我需要开发一个线性搜索算法来测试数组是否包含testVal
这是我写的
bool Contains(int a[], int arraySize, int testVal)
{
bool contains = 0;
for (int i = 0; i < arraySize; ++i)
{
if (a[i] == testVal)
{
contains = true;
std::cout << "true" << std::endl;
}
else if (a[i] != testVal)
{
contains = false;
std::cout << "false" << std::endl;
}
}
return contains; }
当它调试时它打印正确,但它也打印 19 "false"。我想这与数组大小为 20 有关。我不知道如何将其修复为只打印一次而没有 19“假”。谁能告诉我怎么了?
【问题讨论】:
-
想想找到值后如何停止循环。