【发布时间】:2021-06-27 23:23:51
【问题描述】:
我应该创建一个程序,要求用户填充大小为 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;
}
最后一个函数,它是一个布尔函数,并没有像我想象的那样执行。我认为通过执行array[k] 无论索引k 是什么,它都应该吐出数组中的元素,然后使用表达式if(array[k] == SearchNum) 它应该像if(element == SearchNum) 一样工作,但情况似乎并非如此,输出总是假的。
【问题讨论】:
-
在调试器中单步执行您的程序,并注意执行流程与您预期的不同之处。
-
@chris 是的,对不起,我应该声明我不在您的标准 IDE 中编程。我使用replit.com。我正在下载 Visual Studio 的过程中(当我完成输入时),因为如果没有适当的调试器,我无法完成我的 CS 作业需要更多时间。
-
在这种情况下,有些人喜欢使用的另一种策略是添加打印语句来检查执行流程和值,直到问题缩小到特定的行或其他小代码单元。
-
一些可能有帮助的问题:如果数组的大小为 0 会发生什么?如果搜索匹配数组中的最后一项怎么办?如果它匹配第一个但不匹配最后一个怎么办?它可以匹配数组中的多个条目吗?
-
@chris 谢谢你的帮助。我确实尝试过做同样的策略,我想我到了某个地方!给您添麻烦了!
标签: c++ arrays function if-statement