设计⼀个函数模板, 实现从 int、float、double、char 类型的数组中找出最⼤值元素
时间: 2023-12-26 22:04:29 浏览: 35
好的,我可以为您设计一个函数模板,实现从 int、float、double、char 类型的数组中找出最大值元素。代码如下:
```
template<typename T> T findMax(T arr[], int size) {
T maxElement = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
return maxElement;
}
```
您可以按照以下方式使用它:
```
int intArr[] = {1, 2, 3, 4, 5};
float floatArr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
double doubleArr[] = {1.11, 2.22, 3.33, 4.44, 5.55};
char charArr[] = {'a', 'b', 'c', 'd', 'e'};
int intMax = findMax(intArr, 5);
float floatMax = findMax(floatArr, 5);
double doubleMax = findMax(doubleArr, 5);
char charMax = findMax(charArr, 5);
std::cout << "intMax: " << intMax << std::endl;
std::cout << "floatMax: " << floatMax << std::endl;
std::cout << "doubleMax: " << doubleMax << std::endl;
std::cout << "charMax: " << charMax << std::endl;
```
输出结果为:
```
intMax: 5
floatMax: 5.5
doubleMax: 5.55
charMax: e
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)