设计一个函数模板,用于求一个数组的最大值与最小值。其中数组的元素个数是10,元素的值是随机的。 c++

2024年11月22日 19:42
有3个网友回答
网友(1):

#include

using namespace std;

template
void f(const T (&a)[10],T& max,T& min) {
max=min=a[0];
for (int i=1; i<10; i++) {
if (a[i]>max)
max=a[i];
if (a[i] min=a[i];
}
};

int main () {
int a[10]= {0,1,2,3,4,5,6,7,8,9},imax,imin;
double b[10]= {0.5,1.21,98.1,3.6,4.8,5.7,6.45,7.99,8.3,2.6},dmax,dmin;
f(a,imax,imin);
cout< f(b,dmax,dmin);
cout< return 0;
}

网友(2):

#include
using namespace std;
int len = 0;

template
void fun(T a[],T &max,T &min)
{
max = a[0];
min = a[0];
for(int i=1;i {
if(a[i] > max) max = a[i];
if(a[i] < min) min = a[i];
}
}
void main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
len = 10;
int max,min;
fun(a,max,min);
cout << "最大值:"<< max << " " << "最小值:"<< min << endl;

double b[10] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.1};
double max2,min2;
fun(b,max2,min2);
cout << "最大值:"<< max2 << " " << "最小值:"<< min2 << endl;

}

希望对你有帮助...

网友(3):

Private Sub Form_Load()
Dim l(9) As Integer
For i = 0 To 9
l(i) = i
Next

Debug.Print GETMAXMIN(l)

End Sub
Function GETMAXMIN(a() As Integer) As String
Dim x, z
z = 0
x = 0
For i = LBound(a) To UBound(a)
If a(i) > x Then
x = a(i)
End If
Next
For j = LBound(a) To UBound(a)
If a(j) < z Then
z = a(j)
End If
Next

GETMAXMIN = "The max is " & x & Chr(13) & "The min is " & z

End Function