编写一个程序用来分别求2个整数,3个整数、2 个双精度数三个双精度数的最大值,要求用重载函数来完成
时间: 2023-04-02 19:01:42 浏览: 151
您好,我可以回答您的问题。以下是代码实现:
#include <iostream>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
int max(int a, int b, int c) {
return max(max(a, b), c);
}
double max(double a, double b) {
return a > b ? a : b;
}
double max(double a, double b, double c) {
return max(max(a, b), c);
}
int main() {
int a = 10, b = 20, c = 30;
double d = 1.5, e = 2.5, f = 3.5;
cout << "Max of 2 integers: " << max(a, b) << endl;
cout << "Max of 3 integers: " << max(a, b, c) << endl;
cout << "Max of 2 doubles: " << max(d, e) << endl;
cout << "Max of 3 doubles: " << max(d, e, f) << endl;
return ;
}
相关问题
编写一个程序,用来分别求2个整数、3个整数、2个双精度数和3个双精度数的最大值。要求:使用函数重载来完成。
```c++
#include <iostream>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
int max(int a, int b, int c) {
return max(max(a, b), c);
}
double max(double a, double b) {
return a > b ? a : b;
}
double max(double a, double b, double c) {
return max(max(a, b), c);
}
int main() {
int a = 3, b = 7, c = 5;
double x = 3.14, y = 2.718, z = 1.414;
cout << "max(" << a << ", " << b << ") = " << max(a, b) << endl;
cout << "max(" << a << ", " << b << ", " << c << ") = " << max(a, b, c) << endl;
cout << "max(" << x << ", " << y << ") = " << max(x, y) << endl;
cout << "max(" << x << ", " << y << ", " << z << ") = " << max(x, y, z) << endl;
return 0;
}
```
编写重载函数Max1 可分别求取两个整数,三个整数,两个双精度数,三个双精度数的最大值。编写重载函数Max1 可分别求取两个整数,三个整数,两个双精度数,三个双精度数的最大值。
好的,以下是可能符合您要求的 C++ 代码实现:
```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) {
return Max1(Max1(a, b), c);
}
// 求两个双精度数的最大值
double Max1(double a, double b) {
return a > b ? a : b;
}
// 求三个双精度数的最大值
double Max1(double a, double b, double c) {
return Max1(Max1(a, b), c);
}
int main() {
cout << "Max1(3, 4) = " << Max1(3, 4) << endl;
cout << "Max1(3, 4, 5) = " << Max1(3, 4, 5) << endl;
cout << "Max1(3.1, 4.2) = " << Max1(3.1, 4.2) << endl;
cout << "Max1(3.1, 4.2, 5.3) = " << Max1(3.1, 4.2, 5.3) << endl;
return 0;
}
```
在这段代码中,我们使用了函数重载的技术来实现,即通过不同的参数类型或参数个数来区分不同的函数,从而实现同名函数的多态性。
阅读全文