【发布时间】:2020-05-31 11:09:41
【问题描述】:
我有两个数据类型为 double 的数组 - 称为 array1[10] 和 array2[8]。我需要使用线性搜索函数在每个元素的 array1 中搜索 array2。函数声明是
string linSearch (double array1[10], double array2[8]);
如果在array1 中找到了array2,那么我需要打印出它在array1 中的位置的索引。如果找不到,我需要输出为“NA”。此输出必须是分隔的逗号字符串。 例如。
//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}
//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:
2,NA,5,6,0,NA,NA,7
到目前为止,我有以下代码。这是我第一次使用数组,但我仍然难以理解这个概念——比如一旦我定义了函数,我什至如何在主程序中调用它?!无论如何..我的函数定义(不包括主程序)是:
string linSearch (double array1[10], double array2[8])
{
int index1 = 0;
int index2 =0;
int position =-1;
bool found = false;
while (index1<10 && !found && index2<8)
{
if array1[index1] == array2[index2])
{
found = true;
position = index1;
}
index1++;
index2++;
}
return position;
}
对于在另一个数组中搜索一个数组以及如何输出分隔列表以及如何将其连接到我的主程序,我感到非常困惑。任何帮助将不胜感激。谢谢!
【问题讨论】:
-
第二个数组的起始位置是什么?
-
同样在您当前的代码中,即使 array2 中只有一个数字在数组 1 中,您也会返回
-
不,位置是记录搜索值的位置,变量index2是第二个数组的起始位置。
-
@N7c 在第二个中找到一个时显示数组示例。
-
请添加示例输入和示例输出,目前尚不清楚如何从大小为 10 和 8 的数组中获得 4 个条目 (
2,NA,6,7) 的输出
标签: c++ arrays function cout linear-search