编写重载函数min(),分别计算int,double,float,long类型数组中的最小数

  • Post author:
  • Post category:其他


#include<iostream>
using namespace std;
int min(int* a,int n){
int m,i=0;
while(i<n-1){
if(a[i]<a[i+1])
{
a[i+1]=a[i];
}
i++;
};
m=a[i];
return m;
}


double min(double* a,int n){
double m;
int i=0;
while(i<n-1){
if(a[i]<a[i+1])
{
a[i+1]=a[i];


}


i++;
};
m=a[i];
return m;
}


float min(float* a,int n){
float m;
int i=0;
while(i<n-1){
if(a[i]<a[i+1])
{
a[i+1]=a[i];


}
i++;
};
m=a[i];
return m;


}


long min(long* a,int n){
long m;
int i=0;
while(i<n-1){
if(a[i]<a[i+1])
{
a[i+1]=a[i];


}


i++;
};
m=a[i];
return m;
}


void main()
{
int a[3]={1,2,3};
double b[3]={1.1,2.1,3.1};
float c[3]={2.1,2.3,2.4};
long d[3]={1,2,3};
cout << min(a,3) << endl;
cout << min(b,3) << endl;
cout << min(c,3) << endl;
cout << min(d,3) << endl;
}


如果使用模版函数的话会简单很多。。。

#include<iostream>
using namespace std;
template<class T,class T1>
T min(T* a,T1 n){
int m,i=0;
while(i<n-1){
if(a[i]<a[i+1])
{
a[i+1]=a[i];
}
i++;
};
return a[i];
}


void main()
{
int a[3]={1,2,3};
double b[3]={1.1,2.1,3.1};
float c[3]={2.1,2.3,2.4};
long d[3]={1,2,3};
cout << min(a,3) << endl;
cout << min(b,3) << endl;
cout << min(c,3) << endl;
cout << min(d,3) << endl;
}



版权声明:本文为u012651730原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。