C# provides a comprehensive Math class within the System namespace that offers a wide range of mathematical functions and constants for performing various operations. These functions cover a broad spectrum of mathematical concepts, including arithmetic, trigonometry, statistics, and more.
Arithmetic Functions
Arithmetic functions perform basic mathematical operations on numbers. The following are some commonly used arithmetic functions in C#:
Example:
double number1 = 10.5;
double number2 = -4.3;
double absoluteValue = Math.Abs(number2);
double power = Math.Pow(2, 3);
double squareRoot = Math.Sqrt(16);
double maximum = Math.Max(number1, number2);
double minimum = Math.Min(number1, number2);
Console.WriteLine("Absolute value: " + absoluteValue);
Console.WriteLine("Power: " + power);
Console.WriteLine("Square root: " + squareRoot);
Console.WriteLine("Maximum: " + maximum);
Console.WriteLine("Minimum: " + minimum);
Trigonometric Functions
Trigonometric functions deal with the relationships between angles and sides of triangles. The following are some commonly used trigonometric functions in C#:
Example:
double angle = 45.0 * Math.PI / 180.0; // Convert degrees to radians
double sine = Math.Sin(angle);
double cosine = Math.Cos(angle);
double tangent = Math.Tan(angle);
Console.WriteLine("Sine: " + sine);
Console.WriteLine("Cosine: " + cosine);
Console.WriteLine("Tangent: " + tangent);
Statistical Functions
Statistical functions deal with the analysis and interpretation of data. The following are some commonly used statistical functions in C#:
Example:
double number = 3.14159;
double roundedNumber = Math.Round(number, 2); // Round to 2 decimal places
double flooredNumber = Math.Floor(number);
double ceiledNumber = Math.Ceiling(number);
Console.WriteLine("Rounded number: " + roundedNumber);
Console.WriteLine("Floored number: " + flooredNumber);
Console.WriteLine("Ceiled number: " + ceiledNumber);
Mathematical Constants
The Math class provides several predefined mathematical constants, such as:
Example:
double radius = 5.0;
double area = Math.PI * Math.Pow(radius, 2);
Console.WriteLine("Area of a circle with radius 5.0: " + area);
These functions and constants provide a powerful toolkit for performing various mathematical operations in C# programs.