Use one function name for several kinds of arguments.
What to build
Three overloads of largest.
Requirements
- Write
int largest(int, int). - Write
int largest(int, int, int). - Write
double largest(double, double). - Do not change
main.
Input
One line with three whole numbers, then one line with two decimals.
Output
Three lines, printed by main.
Constraints
All the numbers are from -1000 to 1000.
Example
Input:
1 5 3
2.5 1.5
Output:
5
5
2.5
Why it works
The compiler chooses an overload from the number and types of the arguments, so each call goes to the right function.
Examples
Example 1 · Input
1 5 3 2.5 1.5
Expected output
5 5 2.5
Example 2 · Input
9 2 30 -1.5 -2.5
Expected output
9 30 -1.5
Hints
Hint 1
Write three functions, all called largest.
Hint 2
The three-int version can call the two-int version.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int largest(int a, int b) {
return a > b ? a : b;
}
int largest(int a, int b, int c) {
return largest(largest(a, b), c);
}
double largest(double a, double b) {
return a > b ? a : b;
}
int main() {
int a, b, c;
double x, y;
cin >> a >> b >> c >> x >> y;
cout << largest(a, b) << endl;
cout << largest(a, b, c) << endl;
cout << largest(x, y) << endl;
return 0;
}