运行搜索数组

Running a Search Array

本文关键字:数组 搜索 运行      更新时间:2023-10-16

我正在尝试使用目标值从用户输入中搜索整数数组,在这种情况下,称为"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;
}