COMPUTER PROGRAMMING I
Objective 7.03 Apply Built-in Math Class
Functions
Objective/Essential Standard
Essential Standard7.00 Apply Advanced Logic
Indicator7.03 Apply Built-in Math Class Functions (3%)
Math Class Functions
Math Class Functions
The Math class provides programmers with numerous functions.
We will only look at a few of these functions.Abs(num)
Returns the absolute value of a positive or negative number
Sqrt(num) Returns the square root of a number
Sign(num) Returns the sign of a number
Round (num, places) Returns number nearest to the specified value.
Using Abs(num)
The Abs() function works with the following data types: Decimal, Double, Int16, Int32, Int64, SByte, Single
Abs() Function intNum Value after execution
intNum = Math.Abs(4) 4
sngNum = Math.Abs(-4.123)
4.123
intNum = Math.Abs(0) 0
Using Sqrt(num)
Returns the square root of a number as a double
Sqrt() Function dblNum Value after execution
dblNum = Math.Sqrt(4)
2.0
dblNum = Math.Sqrt(0)
0.0
dblNum = Math.Sqrt(-4)
NaN(NaN represents a value that is not a number)
Using Sign(num)
The Sign() function works with the following data types: Decimal, Double, Int16, Int32, Int64, SByte, Single
Sign() Function intNum Value after execution
intNum = Math.Sign(4)
1
intNum = Math.Sign(-4)
-1
intNum = Math.Sign(0)
0
Round Function
The Round() function works with either a decimal or a double. The variable/value that represents the number of places should be an Integer.
Round() Function dblNum Value after execution
dblNum = Math.Round(5.23651, 2)
5.24
decNum = Math.Round(5.23651)
5.0
dblNum = Math.Round(5.5) 6.0
decNum = Math.Round(5.225, 2)
5.23
Note that .5 does round up here.
Try It!
Create a new application called mathExample Save it into the location as instructed by your teacher.
Add the following controls.When the button is clicked, the appropriate answer
should be displayed in the lblAnswer label. When the btnRound is clicked, it should display an input box
to ask for the number of decimal places.
Control Name Text/Items
Label lblPrompt Enter a Number:
Label lblAnswer
Button btnAbs Absolute Value
Button btnSqrt Square Root
Button btnSign Sign
Button btnRound Round It