C++分治法求最大最小值,要求返回两个值,为何我的程序算出来答案不对TAT
#includeusingnamespacestd;intMIN,MAX;doubleMin,Max;templatevoidminmax(TA[10],intlow,i...
#includeusing namespace std;
int MIN,MAX;
double Min,Max;
templatevoid minmax (T A[10],int low,int high,T &min,T &max)
{T max1,min1,max2,min2;
if (high-low==1)
{
if (A[high]>A[low]) {if(A[high]>max) max=A[high];if(A[low]max) max=A[low];if(A[high]<min) min=A[high];}
}
else
{ int mid;
mid=(low+high)/2;
minmax (A,low,mid,min1,max1);
minmax (A,mid+1,high,min2,max2);
min=min1max2 ? max1:max2;
}
}
int main()
{
int A1[8]={1,2,5,6,8,10,32,56};
minmax (A1,0,7,MIN,MAX);
cout<<"min="<<MIN<<" max="<<MAX<<endl;
double A2[8]={1.1,2.2,3.2,4.6,5.3,1.02,9.35,8.36};
minmax (A2,0,7,Min,Max);
cout<<"min="<<Min<<" max="<<Max<<endl;
return 0;
} 展开
int MIN,MAX;
double Min,Max;
templatevoid minmax (T A[10],int low,int high,T &min,T &max)
{T max1,min1,max2,min2;
if (high-low==1)
{
if (A[high]>A[low]) {if(A[high]>max) max=A[high];if(A[low]max) max=A[low];if(A[high]<min) min=A[high];}
}
else
{ int mid;
mid=(low+high)/2;
minmax (A,low,mid,min1,max1);
minmax (A,mid+1,high,min2,max2);
min=min1max2 ? max1:max2;
}
}
int main()
{
int A1[8]={1,2,5,6,8,10,32,56};
minmax (A1,0,7,MIN,MAX);
cout<<"min="<<MIN<<" max="<<MAX<<endl;
double A2[8]={1.1,2.2,3.2,4.6,5.3,1.02,9.35,8.36};
minmax (A2,0,7,Min,Max);
cout<<"min="<<Min<<" max="<<Max<<endl;
return 0;
} 展开
1个回答
展开全部
#include<iostream>// 引入错误
using namespace std;
int MIN,MAX;
double Min,Max;
template<typename T>
void minmax (T A[10],int low,int high,T &min,T &max)
{
T max1,min1,max2,min2;
if(high == low) // 增加相等时候判断
{
min = A[high];
max = A[high];
}
else if (high-low==1)// 具体操作错误
{
min = A[high] < A[low] ? A[high]:A[low];
max = A[high] > A[low] ? A[high]:A[low];
}
else
{ int mid;
mid=(low+high)/2;
minmax (A,low,mid,min1,max1);
minmax (A,mid+1,high,min2,max2);
min = min1 < min2 ? min1:min2;// 操作错误与操作遗漏
max = max1 > max2 ? max1:max2;
}
}
int main()
{
int A1[8]={1,2,5,6,8,10,32,56};
minmax (A1,0,7,MIN,MAX);
cout<<"min="<<MIN<<" max="<<MAX<<endl;
double A2[8]={1.1,2.2,3.2,4.6,5.3,1.02,9.35,8.36};
minmax (A2,0,7,Min,Max);
cout<<"min="<<Min<<" max="<<Max<<endl;
return 0;
}
修改代码如上,楼主有些语法用错了,然后就是逻辑判断考虑不周全。
运行结果如下:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询