c++ - 运行搜索数组
问题描述
我正在尝试使用目标值从用户输入中搜索整数数组,在这种情况下,称为“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;
}
推荐阅读
- c++ - 在 C++ 中使用来自另一个头文件的抽象类
- c++ - 如何在 websocketpp 中使用自定义记录器?
- javascript - 用#屏蔽字符串
- javascript - 如何比较打字稿中的json数组
- vuejs2 - (VUE / VUEX) 从 API 调用中获取和解析数据的最佳实践
- javascript - 如何使用 Selenium 和 Javascript 修复无法读取 null 错误的属性“点击”
- amazon-web-services - 我应该每次都运行 Glue 爬虫来获取最新数据吗?
- c# - 如何检查 DbMappingViewCache 是否缓存了预编译的视图
- java - 带有 ScrollPane 的 JavaFx 中心进度指示器
- angular - Angular 9 http.get 未执行