C# includes a built-in class named:
MathIt provides useful methods for common calculations.
Instead of writing your own code for every mathematical operation, you can call a method on Math.
Examples include:
Math.Abs(....)
Math.Round(....)
Math.Max(....)
Math.Min(....)Each method performs a specific numeric task.
Earlier, you called instance methods on objects:
team1.DisplayName();The Math class is used differently.
For example:
double distance = Math.Abs(-12.5);You call:
Math.Abs(...)directly through the class name.
You do not create a Math object first.
Consider:
double difference = Math.Abs(-8.5);The result is:
8.5The method returns the non-negative magnitude of the supplied number.
A soccer example might calculate the difference between two positions:
double fieldDifference = Math.Abs(playerX - ballX);The goal is to know how far apart the values are, regardless of which one is larger.
Consider:
int highestScore = Math.Max(homeScore, awayScore);If:
homeScore = 3
awayScore = 1then:
highestScore = 3The method compares the supplied values and returns the larger one.
For:
int lowestScore = Math.Min(homeScore, awayScore);the method returns the smaller value.
These methods can make a calculation easier to read than writing more decision logic for a simple numeric choice.
Suppose:
double average = 7.6;
double roundedAverage = Math.Round(average);The returned value is the rounded numeric result.
The exact rounding behavior can depend on the overload and values involved.
For this activity, focus on the basic idea:
For:
Math.Abs(-8.5)the value:
-8.5is an argument.
For:
Math.Max(homeScore, awayScore)two arguments are supplied.
This connects the Math class to what you already know about method parameters and arguments.
Consider:
double adjustedDistance = Math.Abs(playerX - ballX);C# first evaluates:
playerX - ballXThen that result becomes the argument to:
Math.Abs(....)The value returned by Math.Abs is then assigned to:
adjustedDistanceThis creates a clear flow:
A local variable can hold a calculation result:
double distance = Math.Abs(playerX - ballX);Now the method can use:
distancelater in the same scope.
Local variables are introduced more fully later in this batch.
Ask what the calculation needs.
Use:
Math.Abs(....)Use:
Math.Max(....)Use:
Math.Min(....)Use:
Math.Round(....)Do not choose a method merely because its name looks familiar.
A soccer application may need rules involving:
Those are domain decisions.
The Math class helps with numeric calculations.
Use it when the problem is genuinely mathematical.
A Math call looks like:
Math.MethodName(arguments)It accepts numeric information, performs a defined calculation, and produces a numeric result that your code can use.