The Math
class in C# provides many useful static methods for performing mathematical operations such as rounding, powers, roots, trigonometry, and constants.
Math.Abs(x)
— Returns the absolute value of x
.Math.Pow(x, y)
— Returns x
raised to the power y
.Math.Sqrt(x)
— Returns the square root of x
.Math.Round(x)
— Rounds x
to the nearest integer.Math.Ceiling(x)
— Rounds x
up to the nearest integer.Math.Floor(x)
— Rounds x
down to the nearest integer.
using System;
class Program
{
static void Main()
{
double num = -15.7;
Console.WriteLine(Math.Abs(num)); // 15.7
Console.WriteLine(Math.Pow(2, 3)); // 8 (2³)
Console.WriteLine(Math.Sqrt(49)); // 7
Console.WriteLine(Math.Round(3.6)); // 4
Console.WriteLine(Math.Ceiling(3.1)); // 4
Console.WriteLine(Math.Floor(3.9)); // 3
}
}
C# also supports trig functions in radians:
Math.Sin(angle)
— SineMath.Cos(angle)
— CosineMath.Tan(angle)
— Tangent
double angle = Math.PI / 4; // 45 degrees in radians
Console.WriteLine(Math.Sin(angle)); // ~0.707
Console.WriteLine(Math.Cos(angle)); // ~0.707
Console.WriteLine(Math.Tan(angle)); // ~1
Math.PI
— The constant π (~3.14159)Math.E
— The constant e (~2.71828)Summary
Math
class has many static methods for common math operations.Math.Pow()
for powers, Math.Sqrt()
for roots, and Math.Abs()
for absolute values.Round
, Ceiling
, and Floor
.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!