利用函数模板写一个函数模板,名为max_min_mean。求int数组,float数组和double数组平均值、最大值和最小值。数组大小为5,元素值任意 在main函数中输出(不要在函数中输出)
时间: 2024-05-10 18:18:08 浏览: 102
有一个int数组{1,3,5,-2,4,6},要求获取:最大值、最小值、元素和、平均值
5星 · 资源好评率100%
下面是一个实现 max_min_mean 函数模板的例子:
```cpp
#include <iostream>
#include <algorithm>
template<typename T>
void max_min_mean(T arr[], int size, T& max, T& min, double& mean) {
max = *std::max_element(arr, arr + size);
min = *std::min_element(arr, arr + size);
mean = 0;
for (int i = 0; i < size; ++i) {
mean += arr[i];
}
mean /= size;
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
float arr2[] = {1.5f, 2.5f, 3.5f, 4.5f, 5.5f};
double arr3[] = {1.2, 2.3, 3.4, 4.5, 5.6};
int max1, min1;
double mean1;
max_min_mean(arr1, 5, max1, min1, mean1);
std::cout << "int array: max=" << max1 << ", min=" << min1 << ", mean=" << mean1 << std::endl;
float max2, min2;
double mean2;
max_min_mean(arr2, 5, max2, min2, mean2);
std::cout << "float array: max=" << max2 << ", min=" << min2 << ", mean=" << mean2 << std::endl;
double max3, min3;
double mean3;
max_min_mean(arr3, 5, max3, min3, mean3);
std::cout << "double array: max=" << max3 << ", min=" << min3 << ", mean=" << mean3 << std::endl;
return 0;
}
```
输出结果为:
```
int array: max=5, min=1, mean=3
float array: max=5.5, min=1.5, mean=3.5
double array: max=5.6, min=1.2, mean=3.4
```
阅读全文