+ 2
76.2 Practice - Function Templates
You need to write a function, which returns the maximum of its two parameters, and it should work for different data types (integers, doubles, etc.) Create a function template called myMax(), which takes two parameters and returns the larger one, so that the code in main works as expected. Sample Input 4.2 8.1 Sample Output 8.1 *Remember, the syntax for declaring a template function is template <class T> My code is below. I have run out of ideas. Please help.
7 Réponses
+ 2
#include <iostream>
using namespace std;
template<class T>
T myMax(T a, T b)
{
return a > b ? a : b;
}
int main () {
double x, y;
cin>>x>>y;
int a, b;
cin>>a>>b;
cout << myMax(x, y) << endl;
cout << myMax(a, b) << endl;
}
+ 2
#include <iostream>
using namespace std;
template<class T, class X>
T myMax(T a, X b)
{
return (T)(a > b ? a : b);
}
int main () {
double x;
int y;
cin>>x>>y;
cout << myMax(x, y) << endl;
}
This is a correct answer and runit code
+ 1
#include <iostream>
using namespace std;
//your code goes here
template <class T>
T myMax(T a, T b)
{
return (a > b ? a : b);
}
int main () {
double x, y;
cin>>x>>y;
int a, b;
cin>>a>>b;
cout << myMax(x, y) << endl;
cout << myMax(a, b) << endl;
}
Good Luck
0
#include <iostream>
using namespace std;
//your code goes here
template <class T>
T myMax(int a, int b)
{
return (a < b ? a : b);
}
int main () {
double x, y;
cin>>x>>y;
int a, b;
cin>>a>>b;
cout << myMax(x, y) << endl;
cout << myMax(a, b) << endl;
}
0
mabey the parameters should be of the template type as well... your code only takes integers as arguments.
0
#include <iostream>
using namespace std;
template<class T>
T myMax(T a, T b)
{
return a > b ? a : b;
}
int main () {
double x, y;
cin>>x>>y;
int a, b;
cin>>a>>b;
cout << myMax(x, y) << endl;
cout << myMax(a, b) << endl;
}
- 2
Thanks Jay Matthews