Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 运行搜索数组_C++ - Fatal编程技术网

C++ 运行搜索数组

C++ 运行搜索数组,c++,C++,我试图使用一个目标值从用户输入中搜索一个整数数组,在本例中称为“searchArray”。每次我运行一个值为{1 5 9 7 3}的5维数组,搜索目标值为9的数组时,它会打印出索引2处找到的值9的正确信息,并进行3次检查!在数组中找不到值v!。我需要v值的最后一部分不要打印出来。我觉得我为if-else语句设置了正确的范围,但出于某种原因,它仍然打印出数组中找不到的内容,即使是。 首先,您可能会更改if条件,因为您已经测试了一次searchArray==arr[i] 为了检查是否找到了值,我可

我试图使用一个目标值从用户输入中搜索一个整数数组,在本例中称为“searchArray”。每次我运行一个值为{1 5 9 7 3}的5维数组,搜索目标值为9的数组时,它会打印出索引2处找到的值9的正确信息,并进行3次检查!在数组中找不到值v!。我需要v值的最后一部分不要打印出来。我觉得我为if-else语句设置了正确的范围,但出于某种原因,它仍然打印出数组中找不到的内容,即使是。


首先,您可能会更改if条件,因为您已经测试了一次searchArray==arr[i]

为了检查是否找到了值,我可能会使用布尔值

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;
}

请修复缩进。对于“最佳”、“最差”和“未找到”这三种情况,您有一个输出并执行中断,但对于“未找到”和“最差”这三种情况,您不会退出循环,因此您将继续搜索。您需要通过在您认为不应该发生的“如果”条件中设置断点来调试代码。
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;
}