【发布时间】:2012-06-08 07:52:58
【问题描述】:
我有以下代码顺序搜索在 Visual C++ 中完美运行
#include<iostream>
using namespace std;
int seqSearch(int list[], int length, int item)
{
int index = length-1;
if (index < 0)
return -1;
if (list[index] == item)
return (index);
else seqSearch(list, index, item);
} // end seqSearch
int main ()
{
int const length = 10;
int item;
int list[10] = { 2, 3, 4, 5, 20, 40, 80, 45, 99, 0};
cout << "Please enter the value to be searched: ";
cin>> item;
if (seqSearch(list, length, item) == -1) cout << "Item not found." << endl;
else cout <<"Item found at position: " << seqSearch(list, length, item) << " of list *Note: (first index of list start at 0)" << endl;
system("pause");
return 0;
}
但在 Dev-C++ 中它总是显示结果 0,我尝试调试并查看索引是正确的,但为什么它显示 0?为什么我们在 VC++ 和 Dev-C++ 之间存在这种差异?
【问题讨论】:
-
递归顺序搜索??
-
else seqSearch(list, index, item);没有返回任何内容。将其更改为else return seqSearch(list, index, item);。 -
很可能与您的问题无关,但您可能希望查看 Dev-C++ 以外的其他 IDE 以获取 reasons listed here。
-
Vikas 是对的,添加 else return seqSearch(list, index, item);我如何接受你的回答?
-
顺便说一句,你不应该看到不同的行为。是不是搞错了?
标签: c++ algorithm visual-c++ recursion dev-c++