Math Functions

StevenSwiniarski's avatar
Published Jan 25, 2023Updated Mar 22, 2023
Contribute to Docs

Mathematical functions can be performed using the System.Math class. System.Math is a static class that is included within .NET as part of the System namespace. .NET is a free, cross-platform, open source developer platform created by Microsoft.

Syntax

The Math class can be accessed by including the System namespace within a .cs file by adding the following line:

// Include the System namespace
using System;

The Math class is static and is accessed without needing to create an instance.

Example

The following example uses the Math.Pow() method to return the result of 4 raised to the power of 2:

// Include the System namespace
using System;
public class Example
{
public static void Main(string[] args)
{
// Raise 4 to power of 2
double x = Math.Pow(4,2);
System.Console.WriteLine("x = {0}", x);
// Output: x = 16
}
}

In cases where access to System.Math is required but access to the entire System namespace is not, an alternative syntax can be used instead. The following example uses an alternative syntax and returns the floor of 3/2 using the System.Math.Floor() method:

public class Example
{
public static void Main(string[] args)
{
// Round down the result of 3/2
double x = System.Math.Floor((double)3/2);
System.Console.WriteLine("x = {0}", x);
// Output: x = 1
}
}

Below are a selected list of System.Math methods:

Math Functions

.Abs()
Returns the absolute value of a given number.
.Acos()
Returns the inverse cosine of the argument.
.Asin()
Returns an angle in radians whose sine is a specified number.
.Atan()
Returns the inverse tangent of the argument.
.Atan2()
Returns the angle, in radians, between the positive x-axis and the vector to point (x, y).
.Ceiling()
Returns the smallest integer which is greater than or equal to a given number.
.Cos()
Returns the cosine of a given angle.
.Cosh()
Returns the hyperbolic cosine of a given angle.
.Exp()
Returns the result of raising e to the power of a specific number.
.Floor()
Returns the largest whole integer which is less than or equal to the given number.
.Max()
Returns the greater of two specified numbers.
.Min()
Returns the smaller of two specified numbers.
.Pow()
Returns the result of a given number raised to the power of a second number.
.Round()
Returns a value rounded to the nearest integer.
.Sin()
Returns the sine of a given angle.
.Sinh()
Returns the hyperbolic sine of a given angle.
.Sqrt()
Returns the square root of the given number.
.Tan()
Returns the tangent of a given angle.
.Tanh()
Computes the hyperbolic tangent of a given angle in radians.

All contributors

Contribute to Docs

Learn C# on Codecademy