EN
C# / .NET - Math.Max() method example
0 points
The Math.Max()
function returns the highest number from given numbers.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(string[] args)
6
{
7
int max = Math.Max(2, 5);
8
Console.WriteLine( max ); // 5
9
10
Console.WriteLine( Math.Max(1, 2) ); // 2
11
Console.WriteLine( Math.Max(1.5, 2.0) ); // 2
12
13
Console.WriteLine( Math.Max(2, Double.NaN) ); // NaN
14
}
15
}
Syntax |
xxxxxxxxxx 1 namespace System 2 { 3 public static class Math 4 { 5 // ... 6 public static byte Max(byte val1, byte val2) { ... } 7 public static decimal Max(decimal val1, decimal val2) { ... } 8 public static double Max(double val1, double val2) { ... } 9 public static short Max(short val1, short val2) { ... } 10 public static int Max(int val1, int val2) { ... } 11 public static long Max(long val1, long val2) { ... } 12 public static sbyte Max(sbyte val1, sbyte val2) { ... } 13 public static float Max(float val1, float val2) { ... } 14 public static ushort Max(ushort val1, ushort val2) { ... } 15 public static uint Max(uint val1, uint val2) { ... } 16 public static ulong Max(ulong val1, ulong val2) { ... } 17 // ... 18 } 19 } |
Parameters | val1, val2 - values to compare. |
Result |
Maximal It returns |
Description | Max is a static method that takes number arguments and returns the biggest 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 max = array.Max();
11
Console.WriteLine( max ); // 16
12
}
13
}
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
static double Max(double[] array)
6
{
7
double result = Double.NegativeInfinity;
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( Max( numbersArray ) ); // 16
20
}
21
}