女儿数学里有一题如题,求最大和最小。用C++来实现,各位朋友是否有更好的算法?
#include<iostream>
#include<cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
int x[5]={1,2,5,6,8};
int a,b,c,d,e;
int min,max,num;
int count=1;
min=1000000;
max=0;
int min1,min2;
int max1,max2;
for (a=0;a<=4;a++){
for (b=0;b<=4;b++){
for (c=0;c<=4;c++){
for (d=0;d<=4;d++){
for (e=0;e<=4;e++){
if (a!=b && a!=c && a!=d && a!=e )
if ( b!=c && b!=d && b!=e )
if ( c!=d && c!=e )
if ( d!=e ){
num=(x[a]*100+x[b]*10+x[c])*(x[d]*10+x[e]);
if (min>num) {
min=num;
min1=x[a]*100+x[b]*10+x[c];
min2=x[d]*10+x[e];
}
if (num>max) {
max=num;
max1=x[a]*100+x[b]*10+x[c];
max2=x[d]*10+x[e];
}
cout<<"第"<<count++<<"个值:";
cout<<x[a]<<x[b]<<x[c]<<x[d]<<x[e]<<":";
cout<<num<<endl;
}
}
}
}
}
}
cout<<"最大值:"<<max1<<"*"<<max2<<":"<<max<<endl;
cout<<"最小值:"<<min1<<"*"<<min2<<":"<<min<<endl;
return 0;
}
结果如下:
