This is a simple introduction course question. I have to write a program that asks the user to input 3 numbers, and determines the largest and smallest number.
I need to only use if
statements.
This is what I tried so far: which required 4 comparisons.
int x, y, z;
int smallest, largest;
cout << "Please enter 3 numbers to compare: " ;
cin >> x >> y >> z;
smallest = x;
largest = x;
if (y > largest)
largest = y;
if (z > largest)
largest = z;
if (y < smallest)
smallest = y;
if (z < smallest)
smallest = z;
cout << "largest: " << largest << ", and smallest: " << smallest << endl;
My question is: Is it possible to only use 3 comparisons, or less? I think when y > largest
, it also tells us something else as well?
The issue with your code is that you toss out a lot of information. In "challenges" such as these, you have to make the most of what you have. So when you say, for example
if (y > largest)
don't just treat the true
case. Also try to reason about the case when the condition doesn't hold.
if ( x < y )
{
smallest = x;
biggest = y;
}
else
{
smallest = y;
biggest = x;
}
if ( z < smallest )
smallest = z;
else if ( z > biggest )
biggest = z;
This contains only 3 comparisons.
Why are you checking if (y < smallest)
? At this point in the flow, smallest
must be x
, but you've already checked if y > x
in the first condition (if (y > largest)
), so the third condition is redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With