Skip to content

Math

Arithmetic Operators

arithmetic operators are used to perform various mathematical operations on numeric values. These operators allow you to perform addition, subtraction, multiplication, division, and other arithmetic calculations. Here are the basic arithmetic operators in C#:

  • Binary: + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Reminder)
  • Unary: ++ (Increment), -- (Decrement)

These operators can be used with various numeric data types, including int, double, float, decimal, etc. The behavior of these operators might vary depending on the specific data types involved in the operation. For example, division involving integers results in integer division, while division involving floating-point numbers results in floating-point division.

C#
int integerResult = 10 / 3;
// Result: 3 (integer division)

double doubleResult = 10.0 / 3.0; 
// Result: 3.3333333333333335 (floating-point division)

It's important to understand the data types and potential data type conversions when working with arithmetic operators to avoid unintended consequences such as loss of precision or unexpected results.

Math Class

The Math class in C# is part of the System namespace and provides a set of static methods for performing common mathematical operations. These methods cover a range of mathematical functions, including basic arithmetic operations, trigonometry, logarithms, exponentiation, rounding, and more. The Math class is designed to provide a standard set of mathematical functions that are commonly used in programming.

The System.Math class is used for common mathematical functions not easily done with the arithmetic operators.

C#
double radius = 4.5;
double area = Math.PI * Math.Pow(radius, 2);

Console.WriteLine("Area: {0}", area);

Output:

Text Output
Area: 63.6172512351933

Info

It's important to note that the Math class methods operate with the double data type, so when using these methods, ensure that your data types are compatible. Additionally, be aware of potential issues related to floating-point precision in certain mathematical operations.

Tip

It's also recommended to familiarize yourself with the Math class members for the programming language you are working with.

Further Reading