Home > Net >  How to find 1st and 2nd smallest number out of 3 variables C#
How to find 1st and 2nd smallest number out of 3 variables C#

Time:10-09

decimal angle1 = decimal.Parse(angle1_textbox.Text);
decimal angle2 = decimal.Parse(angle2_textbox.Text);
decimal angle3 = decimal.Parse(angle3_textbox.Text);

How to find the smallest 2 numbers from this?

CodePudding user response:

The shortest form would be

var min1 = Math.Min(angle1, angle2);
var min2 = Math.Min(Math.Max(angle1, angle2), angle3);
var tuple = Tuple.Create(Math.Min(min1, min2), Math.Max(min1, min2));

So the first element of tuple is the smallest, the second is second smallest.

CodePudding user response:

One way to find the smallest number is to iterate through all the numbers and compare each to the current smallest number found. If it's smaller, replace the current smallest with that number and continue. The placeholder number therefore must be initialized with the largest possible value so it's immediately replaced by the first value in the array.

For example:

public static void Main()
{
    decimal angle1 = decimal.Parse("1");
    decimal angle2 = decimal.Parse("2");
    decimal angle3 = decimal.Parse("3");
    
    // Put the numbers into an array so we can loop over them
    decimal[] numbers = {angle1, angle2, angle3};
    
    // To start, set our two placeholders to the largest possible values
    decimal smallest = decimal.MaxValue;
    decimal secondSmallest = decimal.MaxValue;
    
    // Loop through our set of numbers and replace the 
    // placeholders when a smaller number is encountered
    foreach(decimal number in numbers)
    {
        if (number < smallest)
        {
            secondSmallest = smallest;
            smallest = number;
        }
        else if (number < secondSmallest)
        {
            secondSmallest = number;
        }
    }
    
    Console.WriteLine($"smallest: {smallest}");
    Console.WriteLine($"second smallest: {secondSmallest}");
}
  •  Tags:  
  • c#
  • Related