We have a program to do where you have to find the largest and smallest number in 5 values. I was able to make the smallest work using what our teacher calls "nested function calls". I cannot get largest to work even though its the exact opposite, in theory it should work. We are not allowed to use arrays and the functions are value returning functions. Do not return through pass by reference. Each function returns a single value. No global variables.
we have to find the largest and smallest of 5 numbers.
//functions
float larger(float x, float y) //finding the largest number
{
if(y>x)
{
return y;
}
}
float smaller(float x, float y) //finding the smallest number
{
if(y<x)
{
return y;
}
}
//calls made in main
largest=larger(larger(a,b),(larger(c,d),e));
cout<<"\nThe largest number is: "<<largest<<endl;
smallest=smaller(smaller(a,b),(smaller(c,d),e));
cout<<"\nThe smallest number is: "<<smallest<<endl;
I thought return y was returning something? When I test the data with a series of 5 numbers, say, 10, 20, 30, 40, 50. For smallest it gives: 10, but for largest it usually does either 20 or 40. I change up the order sometimes to make sure it is working.
We can unpack it a bit more to emphasize the point:
1 2 3 4 5 6 7 8
// from
largest = larger( larger(a,b), (larger(c,d),e) );
// to
ab = larger(a,b)
cd = larger(c,d)
xe = cd, e; // read about comma-operator
largest = larger( ab, xe );
It's not missing much: largest = larger( larger(a,b), larger(larger(c,d),e) );
While arrays are not required, one could test with one:
1 2 3 4 5 6 7 8 9 10 11 12
constexprint N {5};
float data[N] {a, b, c, d, e}
for ( int k=0; k<N; ++k ) {
float ax = data[k];
float bx = data[(k+1)%N];
float cx = data[(k+2)%N];
float dx = data[(k+3)%N];
float ex = data[(k+4)%N];
largest = larger( larger(ax, ab), larger( larger(cx, dx), ex ) );
std::cout << largest << '\n';
}
The result should be same every time.
The main point is that one successful test does not prove that something "works".
Thanks guys. Thanks keskiverto for showing me that I was missing one more "larger" in there after the (a,b),
Thank you to everyone else. I managed to get it working by adding else statements in the functions and adding the extra words. I have tried it using any combination of data and it finds the highest and lowest.