c++ 二分搜索算法总是出错,不知道问题出在哪里

C++语言 码拜 8年前 (2016-09-23) 1848次浏览
用的vc++,总觉得本人的vc++总是有问题。
#include <iostream.h>
template<class Type>
//改写二分搜索算法
int ReBinarySearch(Type a[],const Type& x,Type left,Type right,Type &i,Type &j)
{
while(left<=right){
Type middle=(left+right)/2;
if(x==a[middle]){
i=j=middle;
return 1;
}
if(x>a[middle]){
left=middle+1;
}else{
right=middle-1;
}
}
i=right;
j=left;
return 0;//未找到x
}
void main(int argc, char* argv[])
{
int a[5]={0,1,2,4,5};
int x=3;
int i,j,k;
k=ReBinarySearch(a,x,0,4,i,j);
if(k==1){
cout<<“found x”<<endl;
}else{
count<<“not found x”<<endl;
}
count<<“i=”<<i<<endl;
count<<“j=”<<j<<endl;
}
错误:
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(26) : error C2065: “Type” : undeclared identifier
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(26) : error C2146: syntax error : missing “)” before identifier “a”
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(26) : error C2059: syntax error : “)”
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(27) : error C2143: syntax error : missing “;” before “{”
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(27) : error C2447: missing function header (old-style formal list?)
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(50) : error C2064: term does not evaluate to a function
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(54) : error C2065: “count” : undeclared identifier
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(54) : error C2297: “<<” : illegal, right operand has type “char [12]”
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(56) : error C2297: “<<” : illegal, right operand has type “char [3]”
E:\Su\计算机算法设计与分析\BinarySearch\BinarySearch.cpp(57) : error C2297: “<<” : illegal, right operand has type “char [3]”
执行 cl.exe 时出错.
BinarySearch.exe – 1 error(s), 0 warning(s)
解决方案

10

模板好像没有识别,估计头文件有问题!别用c语言相似的头文件,不要.h…

5

本人编译了一下,环境vc6.0,除了count拼写错误外,没有报错

2

程序员的常识之一:不要将程序源代码或项目或exe放在复杂(带空格和汉字)的目录下。

18

#include <iostream.h> //过时了
//改用
#include <iostream>
using namespace std; //其实这个也过时了,已经被列为不推荐之列了
//如今推荐
using std::cout;
///或直接用 
std::cout <<"312"<<std::endl;

5

cout  写成 count,,,
–题外话–
这个真没看到,看来老外说的有道理,
拼写相似的名字,心理距离比较小,应该避免在一起用

10

你用的是VC6吗,假如是建议换VS试下,VC6太老了

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c++ 二分搜索算法总是出错,不知道问题出在哪里
喜欢 (0)
[1034331897@qq.com]
分享 (0)