int highest(int a, int b, int c, int d)
{
if (a > b)
{
if (a > c)
{
if (a > d)
{
return a;
}
elsereturn d;
}
}
elseif (b > c)
{
if (b > d)
{
return b;
}
elsereturn d;
}
}
I see no reason for errors in this function, you should put the rest of your code.
#include <iostream>
#include <algorithm>
usingnamespace std;
template<typename T> T largest( T a, T b)
{
return a > b ? a : b;
}
template<typename T, typename... Tail> T largest( T a, Tail... b )
{
return largest( a, largest( b... ) );
}
int main()
{
int a = 1, b = 3, c = 2, d = -2;
cout << largest( a, b, c, d ) << '\n';
cout << max( { a, b, c, d } ) << '\n';
}
int getLargest(int a, int b, int c, int d)
{
if (a > b)
{
if (a > c)
{
if (a > d)
{
return a;
}
elsereturn d;
}
if (c > d)
return d;
elsereturn c;
}
if (b > c)
{
if (b > d)
return b;
elsereturn d;
}
if (c > d)
return c;
elsereturn d;
}
int highest( int a, int b, int c, int d )
{
int highest_so_far = a ;
if( b > highest_so_far ) highest_so_far = b ; // higher of a and b
if( c > highest_so_far ) highest_so_far = c ; // highest of a,b and c
if( d > highest_so_far ) highest_so_far = d ; // highest of a,b,c and d
return highest_so_far ;
}
Or
1 2 3 4 5
// using the library: #include <algorithm> (you may ignore this for now)
constexprint highest( int a, int b, int c, int d )
{
return std::max( { a, b, c, d } ) ;
}
int highest(int a, int b, int c, int d)
{
if (a > b)
{
if (a > c)
{
if (a > d)
{
return a;
}
elsereturn d;
}
}
elseif (b > c)
{
if (b > d)
{
return b;
}
elsereturn d;
}
elseif (c > d)
{
return c;
}
elsereturn d;
}
int highest(int a, int b, int c, int d)
{
if (a > b)
{
// the only thing we know so far is that b is not the largest
// we have to compute highest(a, c, d) here
}
else
{
// the only thing we know so far is that a is not the largest
// we have to compute highest(b, c, d) here
}
}
Writing all the nested conditions makes code long and complex.
Look at the solution by JLBorges. There are only 3 tests.
@salem c: In this specific case there are power-of-two operands. One could: return std::max( std::max(a, b), std::max(c, d) );