我的bool函数一直返回true,我不知道为什么



我正在做一份练习表来了解函数,目前我正在处理以下问题。

为以下各项编写功能原型:

  1. 一个函数HasValue,可以传递对数组的引用、数组的大小和搜索值。如果数组中存在搜索值,则函数应返回true

在我的代码中,我已经将数组的内容、数组大小和要在数组中搜索的值发送到bool函数。

在函数中,我使用for循环将值与数组的每个元素进行比较。

然后,我在函数中创建了一个变量计数,如果值与数组中的任何元素匹配,该计数将递增。

然后,如果count大于0,我使用if-else语句返回true,如果count等于0,则返回false。然而,问题是函数只返回true,因此输出将始终是"此数字出现在数组中">

从逻辑上讲,这些步骤对我来说似乎是正确的,但显然有一个我看不到的缺陷。我想只是我对Bool函数还没有很好的理解,但如果有人能解释我在哪里出错以及为什么出错,我将在学习过程中理解函数和c++。

#include <iostream>
#include <iomanip>
#include "stdafx.h"
using namespace std;
bool HasValue(int Array[], int size, int Value);
int main()
{
int value;
int Array[10]{ 3,5,6,8,9,1,2,14,12,43 };
cout << "enter value you wish to search for in array " << endl;
cin >> value;
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
return 0;
}
bool HasValue(int Array[], int size, int Value)
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (Value == Array[i])
{
count++;
}    
}
if (count > 0)
{
return true;
}
else
return false;
}

您的测试代码是的问题

HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;

这将忽略HasValue的返回值,并始终打印"This number appears in the array"

HasValue(Array, 10 , value);

这行代码执行函数,但忽略返回的值。当函数返回一个值时,您需要将其分配给一个变量:

bool result = HasValue(Array, 10 , value);

if (true)对返回的值没有任何引用。if中的true将导致第一个cout始终打印。您将永远看不到else的输出。但是,一旦在变量中有了返回值,就可以在if:中使用它

if(result)

如果你想的话,你可以把这一切简化为一行代码:

if(HasValue(Array, 10 , value))

现在if语句将直接测试HasValue()的返回值。在这种特殊的情况下,将代码组合成一行似乎是合理的。不过,你做这件事一定要小心。当您将太多的代码组合成一行时,代码将变得更难调试。当你继续学习如何编程时,你需要在可读性和便利性之间找到平衡。

相关内容

最新更新