运行搜索数组
Running a Search Array
我正在尝试使用目标值从用户输入中搜索整数数组,在这种情况下,称为"searchArray"。每次我运行值为 5 的维度,值为 {1 5 9 7 3},并在目标值为 9 的数组中搜索时,它都会打印出正确的信息"在索引 2 处找到值 9,进行 3 次检查!在数组中找不到值 v!我需要值 v 的最后一部分不打印出来。我觉得我为 if else 语句设置了正确的范围,但由于某种原因,它仍然打印出数组中找不到的内容,即使它是。 输出示例
#include <iostream>
using namespace std;
int main () {
//similar to lab02, except we are searching values through the array
int dimension;
int counter = 0;
//ask size of array from user
cout << "Enter the size of the array: " << endl ;
cin >> dimension;
//check the validity of the dimension sizes
if (dimension < 1 || dimension > 10 ) {
cout << "ERROR: You entered an invalid value for the array size!";
}
//ask the user to enter the values in array size given
int searchArray;
int arr[dimension];
cout <<"Enter the numbers in the array, separated by a space and press enter: ";
for (int i = 0; i < dimension; i++) {
cin >> arr[i];
}
//ask the user to enter the integer to search through array
cout << "Please enter the key to search in the array: ";
cin >> searchArray;
//use for loop to iterate through array while checking searchArray
for (int i = 0; i < dimension; i++) {
counter = counter + 1;
if (searchArray == arr[i]) {
cout << "Found value " << searchArray << " at index " << i << ", taking " << counter << " checks !";
}
if (counter == 1 && searchArray == arr[i]) {
cout << "We ran into the best case scenario! " << endl;
break;
} else if (counter == dimension && searchArray == arr[i]) {
cout << "We ran into the worst-case scenario!" << endl;
break;
}
else if (counter == dimension && searchArray != arr[i]) {
cout << "The value v was not found in the array!" << endl;
break;
}
}
}
首先,您可以更改 if 条件,因为您已经测试了一次searchArray == arr[i]
if (searchArray == arr[i]) {
cout << "Found value " << searchArray << " at index " << i << ", taking " << counter << " checks !";
if (counter == 1) {
cout << "We ran into the best case scenario! " << endl;
}else if(counter == dimension) {
cout << "We ran into the worst-case scenario!" << endl;
}
}
为了检查您是否找到了该值,我可能会使用布尔值
find = false;
for (int i = 0; i < dimension; i++) {
counter = counter + 1;
if (searchArray == arr[i]) {
cout << "Found value " << searchArray << " at index " << i << ", taking " << counter << " checks !";
find = true;
if (counter == 1) {
cout << "We ran into the best case scenario! " << endl;
}else if(counter == dimension) {
cout << "We ran into the worst-case scenario!" << endl;
}
}
}
if (!find){
cout << "The value v was not found in the array!" << endl;
}
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 如何在动态数组上使用搜索函数
- 在 C++ 中搜索动态分配的数组中的出现次数
- 当您在此单词中搜索单词时调整字符数组的大小?
- 在对象数组中搜索字符串并返回相应值的函数
- C++线性搜索算法,确定数组中元素的数量
- 递归二进制搜索与字符串数组
- 变量未在此范围内声明 数组线性搜索
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 运行搜索数组
- 从数组中搜索元素的索引
- 在数组中搜索复杂度高于 O(n) 的元素
- 比较/搜索数组中多个整数的最佳解决方案
- 如何搜索和排序 2D 数组
- 如何在数组中搜索之前已输入的 int 值
- 数组搜索和唯一增值
- 矢量搜索与数组搜索的时间成本
- 每个项目的C 字符串数组搜索输出
- 简单的C++数组搜索
- 针对多个字符串数组搜索字符串