If语句在计算表达式时未访问数组的值(使用索引)

If statement is not accessing the value of an array (using the index) when evaluating the expression

本文关键字:索引 数组 访问 语句 计算 表达式 If      更新时间:2024-05-10

我应该创建一个程序,要求用户填充大小为10的数组。有三种功能,其名称不言自明;一个函数用元素填充数组,第二个函数水平显示数组,第三个函数检查用户输入的数字是否是数组中的元素。

#include<iostream>
#include<iomanip>
void fillUpArray(int array[], int size);
void displayArray(int array[], int size);
bool isNumberPresent(int array[], int size, int SearchNum);

int main(){
int s = 10; //size of array
int A[s]; //array A with size s
int num; //search number

fillUpArray(A, s);

std::cout <<"n";

displayArray(A, s);

std::cout << "n";

std::cout << "Enter a number to check if it is in the array:n";
std::cin >> num;

std::cout << std::boolalpha << isNumberPresent(A, s, num) << std::endl;

return 0;

}

void fillUpArray(int array[], int size)
{
std::cout << "Enter 10 integers to fill up an array, press enter after every number:n";
for(int i = 0; i < size; i++){

std::cin >> array[i];

}

}
void displayArray(int array[], int size)
{
for(int j = 0; j < size; j++){
std::cout << array[j] << "t";
}
}
bool isNumberPresent(int array[], int size, int SearchNum)
{
bool isPresent;
for(int k = 0; k < size; k++){
if(array[k] == SearchNum)
isPresent = true;
else
isPresent = false;
}
return isPresent;
}

最后一个函数是bool函数,它的执行方式并不像我想象的那样。我认为,通过执行array[k],无论索引k是什么,它都应该吐出数组中的元素,然后使用表达式if(array[k] == SearchNum),它应该像if(element == SearchNum)一样工作,但事实并非如此,输出总是错误的。

isNumberPresent函数中的for循环将无条件运行到数组的末尾(直到k等于size(;在该循环的每次运行中,根据当前元素是否与searchNum匹配来设置isPresent变量的值,覆盖上一个值。因此,函数将简单地返回数组中最后一个元素是否与给定的测试编号相同。

您可以简化该函数并消除对局部变量的需要:如果找到匹配项,则立即返回true;如果循环结束时没有找到匹配项,则返回false:

bool isNumberPresent(int array[], int size, int SearchNum)
{
for(int k = 0; k < size; k++){
if(array[k] == SearchNum) return true; // Found a match - we can return immediately
}
return false; // We didn't find a match
}

此外,请注意,可变长度数组(VLA(不是标准C++的一部分,尽管一些编译器(如GNU g++(支持它们(根据C99标准,它们是C语言的部分(。在程序中,由于数组大小只使用一个(固定(值,因此只需限定s是const:,就可以符合标准C++

int main()
{
const int s = 10; //size of array - make this a "const" be 'proper' C++
int A[s]; //array A with size s
//...