If语句在计算表达式时未访问数组的值(使用索引)
If statement is not accessing the value of an array (using the index) when evaluating the expression
我应该创建一个程序,要求用户填充大小为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
//...
相关文章:
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 是否可以使用字符串或字符索引数组
- 为什么在使用字符索引数组时会出现这种不同的行为
- 在具有重复索引的索引数组处更改 ArrayFire 数组
- 使用索引数组订购 ArrayFire Array 的最佳方式
- C++ 中结构的动态索引数组
- 1索引数组上的qsort()正在扰乱索引
- C++ 索引数组打印和删除字符串名称 数组打印
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用
- openGL drawElements - 一个额外的三角形,使用索引数组
- 具有索引数组的地形(高度贴图)LOD
- 通过创建索引数组进行 C++ 排序
- OpenGL:两个顶点数组 + 两个索引数组
- 将索引数组排序为主数组
- 自动循环跳过某些索引数组
- 为静态强制转换的索引数组生成数组
- 重载枚举索引数组的std::get
- 使用c++中的第二个索引数组对数组进行排序
- 给定的零索引数组 &该数组的均衡索引
- CUDA:重新索引数组