编写重载函数Max1 可分别求取两个整数,三个整数,两个双精度数,三个双精度数的最大值。
时间: 2023-09-09 17:08:34 浏览: 107
好的,这个问题也比较简单。下面是代码实现:
```c++
#include <iostream>
using namespace std;
int Max1(int a, int b) {
return a > b ? a : b;
}
int Max1(int a, int b, int c) {
int max_num = a;
if (b > max_num) max_num = b;
if (c > max_num) max_num = c;
return max_num;
}
double Max1(double a, double b) {
return a > b ? a : b;
}
double Max1(double a, double b, double c) {
double max_num = a;
if (b > max_num) max_num = b;
if (c > max_num) max_num = c;
return max_num;
}
int main() {
int a = 1, b = 2, c = 3;
double d = 1.0, e = 2.0, f = 3.0;
cout << "max of 2 integers: " << Max1(a, b) << endl;
cout << "max of 3 integers: " << Max1(a, b, c) << endl;
cout << "max of 2 doubles: " << Max1(d, e) << endl;
cout << "max of 3 doubles: " << Max1(d, e, f) << endl;
return 0;
}
```
输出结果为:
```
max of 2 integers: 2
max of 3 integers: 3
max of 2 doubles: 2
max of 3 doubles: 3
```
我们可以看到,重载函数 `Max1` 可以分别处理不同数量和类型的数据,并且测试结果也证明它们的功能是正确的。
阅读全文