我哪里理解不对?!?!?!?!?!

------------------------------------------------------------------------------------------------------------------------------

 

 

------------------------------------------------------------------------------------------------------------------------------

请输入代码,这样别人可以拷贝到 IDE 去执行。 

你的程序有个小问题。 在可以查询到要找的值的情况下, 你返回的下标是最后一个该值的下标。

例如:在数列 1 2 3 2 1 要查找 1, 你的程序返回的结果会是4, 而不是0。

不知道你是要最后一个值的还是第一个值的。

如果你要找第一个值的, 那么不需要found这个变量, 在找到的时候直接返回下标就好了。

像这样:

int search(const int a[], int size, int target) {
	int index = 0;
	
	while(index < size) 
		if(a[index] == target)
			return index;
		else
			index++;
			
	return -1;
}

更简洁的方法是用for循环, 像这样:

int search(const int a[], int size, int target) {
	for(int i = 0; i < size; i++) 
		if(a[i] == target)	
			return i;
			
	return -1;
}

 

如果你要找最后一个元素的话, 也可以不用found变量, 直接倒序扫描数组就好了

像这样:

int search(const int a[], int size, int target) {
	for(int i = size-1; i >= 0; i--) 
		if(a[i] == target)	
			return i;
			
	return -1;
}

 

如果你使用的C语言, 需要在for循环外定义变量i, 像这样(正序的同理):

int search(const int a[], int size, int target) {
	int i;
	for(i = size-1; i >= 0; i--) 
		if(a[i] == target)	
			return i;
			
	return -1;
}

 

希望能解决你的问题。

#include <iostream>
using namespace std;

int search(const int a[], int size, int target);

int main()
{
    int a[] = {1,2,3,4,5}, size = 5, target;
    
    char ans;
    int result;
    do
    {
        cout << "输入要搜索的数字: ";
        cin >> target;
        
        result = search(a,size,target);
        if (result == -1)
            cout << target << " 不在数组中\n";
        else
            cout << target << " 在位置 "
                 << result << endl;
                 
        cout << "再次搜索?(y/n): ";
        cin >> ans;
    } while (ans != 'n');
}
    
int search(const int a[], int size, int target)
{

    int index = 0;

    bool found;

    while ((!found) && (index < size))

        if (target == a[index])

            found = true;

        else

            index++;
            
    if (found)

        return index;

    else

        return -1;

}

重点

    bool found = false;

    while ((!found) && (index < size))

大致明白你的意思了, 把(!found)去掉后, 程序不是不能运行, 而是死循环了。

 

去掉后判断条件只剩 (index < size), 而如果找到了那个值的话, index 就会一直保持不变, 从而造成死循环。

加上(!found)后, 找到值后found值会改变, 从而退出循环。

单纯删除判断条件(!found)之后,程序陷入死循环,无法跳出while循环。

假设要搜索的是数值1,则第一次进入while循环就找到了,但此时index值没有递增,也就是index的值一直是0,跳不出while循环。

若搜索的数值不在数组里面,则不会出现死循环的情况。

可以使用断点调试的方法一步一步的看程序运行的情况,相信很快就能理解我上面所说的原因。

请及时采纳一个最正确的回答,结束这个提问流程。 

 bool found; 没有赋初值

你理解的 found = false  推到  !found = true 这里没问题。

但是你想要因为上一条成立就删掉 while 中的这个条件是有问题的。

因为 found 在 while 循环中有重新赋值,换句话说 found 是控制是否要循环的其中一个条件,不能删除。这也就是写代码的人想通过 found 的改变停止搜索的意图。

当找到 target 找到,则 found = true, 则 !found == false, 那么 while(false && xxxxx)都不成立,跳出循环。

这样写的目的就是 但凡找到一个 target 就跳出循环,不接着找剩下的数了。

死循环了,找到等于的话index一直不变,就跳出不了while

你while循环的大括号呢???

while (condition) {

    if (true) {

        break;

    }

}

忽略上面,看错了。。。

循环中匹配到后直接return index;