Reputation: 33
I need to input 3 numbers, and then output the highest & lowest of the 3 numbers using IF commands. I have everything working, except I'm getting 1 largest number (correct) and 3 outputs of the lowest number (incorrect). Now I totally understand why they're all being displayed, I just do not know how to fix it. My code, once the integers have been defined by user input, is as follows:
if (num1 > num2 && num1 > num3)
{
Console.WriteLine("Largest Number: " + num1);
}
if (num2 > num3)
{
Console.WriteLine("Smallest Number: " + num3);
}
else
{
Console.WriteLine("Smallest Number: " + num2);
}
and then duplicated 3 times, switching the respective integers. I understand what the issue is, it's that the second if command is correct for all 3 scenarios. I just... don't know how to fix it. I feel like I just need to join these two if statements together somehow but I'm unsure how to do this, or if it's even possible.
Upvotes: 2
Views: 160
Reputation: 11963
To get the largest/lowest the best way is to have a variable to store the current max/min instead of checking every cases (permutation).
Something like
int largest = int.MinValue;
int smallest = int.MaxValue;
if (num1 > largest)
largest = num1;
if (num2 > largest)
largest = num2;
if (num3 > largest)
largest = num3;
if (num1 < smallest)
smallest = num1;
if (num2 < smallest)
smallest = num2;
if (num3 < smallest)
smallest = num3;
//output largest/smallest
Upvotes: 2
Reputation: 3025
You can, and you will have to, on many instances nest blocks. This way, the second if will only be evaluated if the first was evaluated as true.
if (num1 > num2 && num1 > num3)
{
Console.WriteLine("Largest Number: " + num1);
if (num2 > num3)
{
Console.WriteLine("Smallest Number: " + num3);
}
else
{
Console.WriteLine("Smallest Number: " + num2);
}
}
This is only to answer your most immediate problem, that is, the smallest number being displayed more than one time.
You might encounter others, for example, as others mentioned : What if two numbers are equals ?
Upvotes: 3
Reputation: 8208
No if
statements necessary:
Console.WriteLine("Largest Number: " + Math.Max(Math.Max(num1, num2), num3));
Console.WriteLine("Smallest Number: " + Math.Min(Math.Min(num1, num2), num3));
Upvotes: -1