Help with a Template Function

Okay so my question says:

Write template function that returns the maximum of 3 values.

this is what i have but it is not working.


#include <iostream>
using namespace std;

template <class T>
T findMax(T n1, T n2, T n3){
if ((n1 >= n2) && (n1 >= n3))
{
cout<<n1<<endl;
return n1;
}
else if ((n2 >= n1) && (n2 >= n3))
{
cout<<n2<<endl;
return n2;
}
else if ((n3 >= n1) && (n3 >= n2))
{
cout<<n3<<endl;
return n3;
}
}

int main ()
{
double n1, n2, n3;
cout<<"please enter 3 numbers to find a max"<<endl;
cin>>n1>>n2>>n3;
findMax(n1, n2, n3);
return 0;
}


how can i help this raggedy program?
Write template function that returns the maximum of 3 values.


Take into account that according to the assignment the function has to return the maximum. It shall not do something else as for example outputing on the console some values.

1
2
3
4
5
6
7
8
template <class T>
T findMax( T n1, T n2, T n3 )
{
   T max = n1 < n2 ? n2 : n1;
   max = max < n3 ? n3 : max;

   return ( max );
}



EDIT: By the way it would be much better to define function parameters as const references because they are not changed in the function. So the function can be written as follows

1
2
3
4
5
6
7
8
template <class T>
T findMax( const T &n1, const T &n2, const T &n3 )
{
   T max = n1 < n2 ? n2 : n1;
   max = max < n3 ? n3 : max;

   return ( max );
}

Last edited on
first of all THANKS!

Well i got it to work, but i had to cout<<max in the function, i tried to add a line in the main program after i called the function
cout<<max<<endl;
but it said there was something wrong with the "<<"
any ideas
came out with
IntelliSense: no operator "<<" matches these operands
This is being done very simply

int a = 10, b = 20;

std::cout << findMax( a, b ) << std::endl;
Last edited on
Topic archived. No new replies allowed.