EN
C# / .NET - Math.Min() method example
0 points
The Math.Min()
function returns the smallest number from given numbers.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(string[] args)
6
{
7
int min = Math.Min(2, 5);
8
Console.WriteLine( min); // 2
9
10
Console.WriteLine( Math.Min(1, 2)); // 1
11
Console.WriteLine( Math.Min(1.5, 2.0)); // 1.5
12
13
Console.WriteLine( Math.Min(2, Double.NaN)); // NaN
14
}
15
}
Syntax |
xxxxxxxxxx 1 namespace System 2 { 3 public static class Math 4 { 5 // ... 6 public static byte Min(byte val1, byte val2) { ... } 7 public static decimal Min(decimal val1, decimal val2) { ... } 8 public static double Min(double val1, double val2) { ... } 9 public static short Min(short val1, short val2) { ... } 10 public static int Min(int val1, int val2) { ... } 11 public static long Min(long val1, long val2) { ... } 12 public static sbyte Min(sbyte val1, sbyte val2) { ... } 13 public static float Min(float val1, float val2) { ... } 14 public static ushort Min(ushort val1, ushort val2) { ... } 15 public static uint Min(uint val1, uint val2) { ... } 16 public static ulong Min(ulong val1, ulong val2) { ... } 17 // ... 18 } 19 } |
Parameters | val1, val2 - values to compare. |
Result |
Minimal It returns |
Description | Min is a static method that takes number arguments and returns the smallest one value. |
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
4
public class Program
5
{
6
public static void Main(string[] args)
7
{
8
int[] array = new int[] { 1, 5, 2, 16, -5 };
9
10
int min = array.Min();
11
Console.WriteLine(min); // -5
12
}
13
}
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
static double Min(double[] array)
6
{
7
double result = Double.PositiveInfinity;
8
foreach (double currentNumber in array)
9
{
10
if (result > currentNumber) result = currentNumber;
11
}
12
return result;
13
}
14
15
public static void Main(string[] args)
16
{
17
double[] numbersArray = new double[] { 1.4, 5.0, 2.2, 16.0, -5.0 };
18
19
Console.WriteLine(Min(numbersArray)); // -5
20
}
21
}