C# has a few built in classes that can be called directly by the user.
Arrays, collections, strings are only a few.
One of these classes is the
which contains more than just the standard mathematical operations(
In the previous sections we learned how to construct, modify, and use classes to create objects. However built-in C# classes are not allowed to be modified. The fields and methods available are what you get.
Math class is
static methods and
Math Class is
Math methods are all static.
We do not have to instantiate the
Math class in order to use it.
It is part of the
using System that is commonly found in your C# IDEs, like the
When we want to use members of the
Math class, we need to directly call the class then the member name.
However, if we want to do something with the output of this
Math.Round method, we will need to store it in a variable.
static, it cannot create its own instance.
Math class has built-in methods that you can call. We will review a few in this chapter, but for a complete list
you can read the documentation on the
Math Methods Are
Math Class contains several mathematical and trigonometric methods.
|Abs()||Returns the absolute value, or positive value, of a number. Can be used with any numeric type.||
|Max()||Returns larger of 2 numeric types.||
|Min()||Returns smaller of 2 numeric types.||
|Pow()||Returns specified number raised to specified power. Takes
|Round()||Returns number rounded to nearest integral value OR specified number of decimal places||
|Sqrt()||Returns the square root of specified number. Takes
|Truncate()||Removes any decimals and returns interger part of number. Takes
Math Fields Are Constants¶
Having a built in
Math class can be very helpful when it comes to common math elements, such as
One of the benefits of constant values is that you don’t have to memorize them, or define them in a variable. C# stores the value of pi up to 16 decimal places for us. We just need to use dot notaion and we can access this class field.
1 2 3
Console.WriteLine(Math.PI); Console.WriteLine(Math.PI*4); Console.WriteLine(Math.PI + Math.PI);
3.14159265358979 12.5663706143592 6.28318530717959
However, this value is a constant, or
const. You are NOT able to alter it.
const values are fixed and unable to be updated or overwritten.
1 2 3 4 5
Console.WriteLine(Math.PI); double Math.PI = 1234.56; Console.WriteLine(Math.PI);
3.1415926535897931 error CS1525: Unexpected symbol `.', expecting `,', `;', or `='
The error message shows that the compiler was not expecting you to try and update
Again, users are not allowed to update the
||Ratio of circumference of a circle to its diameter.||3.1415926535897931|
12.3.4. Check Your Understanding¶
Which of the following returns
-3 when applied to