分别编写三个同名的函数max,在整数数组,double数组,字符数组中取得其中的最大值并输出,在主函数中调用这三个函数
#include <iostream>
using namespace std;
double max(double* data, int count)
{
if (count <= 0){
return DBL_MIN;//错误代码
}
double maxValue = data[0];
for (int i = 1; i < count; ++i) {
if (maxValue < data[i]){
maxValue = data[i];
}
}
return maxValue;
}
char max(char* data, int count)
{
if (count <= 0) {
return CHAR_MIN;//错误代码
}
char maxValue = data[0];
for (int i = 1; i < count; ++i) {
if (maxValue < data[i]) {
maxValue = data[i];
}
}
return maxValue;
}
int max(int* data, int count)
{
if (count <= 0) {
return INT_MIN;//错误代码
}
int maxValue = data[0];
for (int i = 1; i < count; ++i) {
if (maxValue < data[i]) {
maxValue = data[i];
}
}
return maxValue;
}
int main()
{
int intArray[] = {0, 1,2,3,4,5,6};
double doubleArray[] = {0, 1,2,3,4,5,6};
char charArray[] = { 0, 1, 2, 3, 4, 5 };
std::cout << "int max = " << max(intArray, sizeof(intArray) / sizeof(int)) << endl;
std::cout << "double max = " << max(doubleArray, sizeof(doubleArray) / sizeof(double)) << endl;
std::cout << "char max = " << (int)max(charArray, sizeof(charArray) / sizeof(char));//因为存在不可见的字符,为了不打印出乱码,强制装换为int
int i;
cin >> i;
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
template <typename T, int N>
T max(const T (&a)[N])
{
return *max_element(begin(a), end(a));
}
int main()
{
int a[] = {0, 1, 2, 3, 4};
double b[] = {1.2, -3.4, 4.5, -5.6, 7.8, -9.0};
char c[] = {'a', 'A', 'b', 'B', 'C', 'c'};
cout << max(a) << ' ' << max(b) << ' ' << max(c) << endl;
return 0;
}