The Math library in C# provides developers with various general, trigonometric, statistical, & logarithmic functions and properties in mathematics. This is ready to use, plug and play library. The library inherits from the Object class the super parent class in C#. It resides in the System namespace.
Note: One very important thing to keep in mind is that the properties and methods in Math class are all static, meaning you need not create any object of Math class to invoke them.C# Math Properties
Let us look at the various mathematical properties in the Math library.
1. E4
E is the logarithmic base, specified by the small letter ‘e’ in mathematical equations. This static property holds the value of the natural logarithmic base.
Code:
using System; public class Program { public static void Main() { Console.WriteLine("The value of logarithmic base E is " + Math.E); } }
Output:
2. PI
Pi, popularly written as the symbol p, is the ratio of the circumference of the circle to the diameter (roughly 3.14). This static constant holds the value of p.
Code:
using System; public class Program { public static void Main() { Console.WriteLine("The value of PI is " + Math.PI); } }
Output:
C# Math Functions
Let us look at the various mathematical functions of the C# Math library available at our disposal:
1. Abs-Absolute Function
Returns the absolute value of a given number (integer, decimal, floating-point, etc.). The absolute value of any number is the maximum possible decimal value greater than or equal to 0 but lesser than or equal to the number itself.
Code:
using System; public class Program { public static void Main() { int num1 = 231; double num2 = -1.23456789; Console.WriteLine("The absolute value of {0} is {1} ", num1, Math.Abs(num1)); Console.WriteLine("The absolute value of {0} is {1} ", num2, Math.Abs(num2)); } }
Output:
2. BigMul-Big Multiplication
This Function returns the full multiplication result of two very large integer numbers. It takes two 32 bit integers and returns a 64-bit multiplication result.
Code:
using System; public class Program { public static void Main() { int num1 = Int32.MaxValue; Console.WriteLine("Multiplication of {0}x{0} without Math function - {1}",num1, num1*num1); Console.WriteLine("Multiplication of {0}x{0} by Math BigMul function - {1}",num1, Math.BigMul(num1, num1)); } }
Output:
3. Floor & Ceiling
The floor() and the ceiling() functions return the floor and ceiling values of a specified number. The floor value of any number is the largest integer smaller than or equal to the number itself. The ceiling value of any number is the smallest integer greater than or equal to the number itself.
Code:
using System; public class Program { public static void Main() { double num1 = 548.65; Console.WriteLine("Floor value of {0} is {1}", num1, Math.Floor(num1)); Console.WriteLine("Ceil value of {0} is {1}", num1, Math.Ceiling(num1)); } }
Output:
4. Sin, Cos & Tan
These trigonometric functions provide the sine, cosine and tangent value of the specified angle.
Code:
using System; public class Program { public static void Main() { double angle = 120.5; Console.WriteLine("Sine value of {0} is {1}", angle, Math.Sin(angle)); Console.WriteLine("Cosine value of {0} is {1}", angle,Math.Cos(angle)); Console.WriteLine("Tangent value of {0} is {1}", angle, Math.Tan(angle)); } }
Output:
5. Sinh, Cosh & Tanh–Hyperbole
These trigonometric functions provide the hyperbolic sine, cosine and tangent value of the specified angle.
Code:
using System; public class Program { public static void Main() { double angle = 120.5; Console.WriteLine("Hyperbolic Sine value of {0} is {1}", angle, Math.Sinh(angle)); Console.WriteLine("Hyperbolic Cosine value of {0} is {1}", angle, Math.Cosh(angle)); Console.WriteLine("Hyperbolic Tangent value of {0} is {1}", angle,Math.Tanh(angle)); } }
Output:
6. Asin, Acos & Atan
These trigonometric functions return the angle to which the specified number is the sine, cosine or tangent value.
Code:
using System; public class Program { public static void Main() { double value = 1; Console.WriteLine("The angle of sin({0}) is {1}", value, Math.Asin(value)); Console.WriteLine("The angle of cos({0}) is {1}", value, Math.Acos(value)); Console.WriteLine("The angle of tan({0}) is {1}", value, Math.Atan(value)); } }
Output:
7. DivRem–Division & Remainder
This function calculates the result of a division of two integers. The result is not returned in a fractional value. Rather, the quotient is returned as the return value of the function and the remainder as an output parameter.
Code:
using System; public class Program { public static void Main() { int divisor = 8; int dividend = 45; int remainder = 0; int quotient = Math.DivRem(dividend, divisor, out remainder); Console.WriteLine("{0} divided by {1} results in {2} as the quotient and {3} as the remainder.", dividend, divisor, quotient, remainder); } }
Output:
8. Exp-Exponential
The exp function returns e to the power of the specified number.
Code:
using System; public class Program { public static void Main() { int power = 4; Console.WriteLine("{0} to the power of {1} is {2}.", Math.E, power, Math.Exp(power)); } }
Output:
9. Log, Log2, & Log10-Logarithm
The log function returns the logarithm of a specified number to a specified base. If no base is specified, the default base is e, resulting in the natural logarithm.
Note: Log2 was introduced in .Net Core. This method is not available in the .Net Framework.
Code:
using System; public class Program { public static void Main() { double num1 = 4.5; int new_base = 12; Console.WriteLine("Log({0}) to the base 'e' is {1}.", num1, Math.Log(num1)); Console.WriteLine("Log({0}) to the base 10 is {1}.", num1,Math.Log10(num1)); Console.WriteLine("Log({0}) to the base 2 is {1}.", num1,Math.Log(num1, 2)); Console.WriteLine("Log({0}) to the base {1} is {2}.", num1,new_base, Math.Log(num1, new_base)); } }
Output:
10. Min & Max
These functions compare the two numbers provided and return the smaller number or the larger number of the two.
Code:
using System; public class Program { public static void Main() { double num1 = 4.5; double num2 = -3.4; int num3 = 981; int num4 = 123; Console.WriteLine("Minimum of {0} and {1} is {2}.", num1, num2,Math.Min(num1, num2)); Console.WriteLine("Maximum of {0} and {1} is {2}.", num1, num2,Math.Max(num1, num2)); Console.WriteLine("Minimum of {0} and {1} is {2}.", num3, num4,Math.Min(num3, num4)); Console.WriteLine("Maximum of {0} and {1} is {2}.", num3, num4,Math.Max(num3, num4)); } }
Output:
11. Pow-Power
The pow() function returns the specified number to the specified power.
Code:
using System; public class Program { public static void Main() { int num1 = 11; double num2 = 3.4; Console.WriteLine("{0} to the power {1} is {2}.", num1, num2, Math.Pow(num1, num2)); Console.WriteLine("The cube of {0} is {1}.", num1, Math.Pow(num1, 3)); } }
Output:
12. Round
The round() function, as the name suggests, rounds the specified number to the nearest integer or specified decimal places after the integer.
There are a few important variations of round() function. It takes either two or three arguments.
- The first argument is the number to be rounded.
- The second argument is the number of digits after the decimal point. If this is not specified, the number is rounded to the nearest integer.
- The third argument is the mode of rounding. This is an enumeration of two values derived accessed from the enum MidpointRounding.
The two modes are:
- AwayFromZero: When a number falls halfway between two numbers, it is rounded to the nearest number which is farther from zero.
- ToEven: When a number falls halfway between two numbers, it is rounded to the nearest even number.
If not specified, the mode AwayFromZero is the default mode.
Code:
using System; public class Program { public static void Main() { double num1 = 2.45; double num2 = 24.5; Console.WriteLine("{0} rounded to the nearest integer is {1}", num1, Math.Round(num1)); Console.WriteLine("{0} rounded to the nearest single-point decimal is {1}", num1, Math.Round(num1, 1)); Console.WriteLine("{0} rounded to the nearest single-point decimal away from zero is {1}", num1, Math.Round(num1, 1, MidpointRounding.AwayFromZero)); Console.WriteLine("{0} rounded to the nearest single-point decimal to even is {1}", num1, Math.Round(num1, 1, MidpointRounding.ToEven)); Console.WriteLine("\n{0} rounded to the nearest integer away from zero is {1}", num2, Math.Round(num2, MidpointRounding.AwayFromZero)); Console.WriteLine("{0} rounded to the nearest integer to even is {1}", num2, Math.Round(num2, MidpointRounding.ToEven)); } }
Output:
13. Sqrt-Square Root
This function returns the square root of the given number.
Code:
using System; public class Program { public static void Main() { int num1 = 196; double num2 = 404.1; Console.WriteLine("Square root of {0} is {1}.", num1,Math.Sqrt(num1)); Console.WriteLine("Square root of {0} is {1}.", num2, Math.Sqrt(num2)); } }
Output:
14. Truncate
The truncate function returns an integral part of the specified number. So, in simple terms, it discards anything after the decimal point and returns everything before the decimal point.
Note: Note that this is different from Round function. The round function returns an integer nearest to the number. It may be an integer greater than the number itself. Whereas, Truncate function would always return the integer part of the number as is. E.g. – Round(4.9) results in 5. Truncate(4.9) results in 4.Code:
using System; public class Program { public static void Main() { double num1 = 404.92; Console.WriteLine("Truncated value of {0} is {1}.", num1, Math.Truncate(num1)); Console.WriteLine("Rounded-off value of {0} is {1}.", num1, Math.Round(num1)); } }
Output:
Conclusion
This article covered almost all the mathematical functions provided in the C# Math library. This library proves to be very useful due to the plug-n-play mathematical properties and functions, thereby making development easier.
The above is the detailed content of Math Functions in C#. For more information, please follow other related articles on the PHP Chinese website!

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
