Zebra0.com

csharp functions

C# has a number of built in functions and constants that you can use.
In this lesson, we will look at several that are representative of the functions and constants available to you.

Start a new project and name it Fun. We will; try several functions, using form load to display results.

PI

private void Form1_Load(object sender, EventArgs e)
{
  this.Text = "PI="+ Math.PI;
}

Note that we have used the concatenation operator, +, to paste together the string literal "PI =" and the value of the constant PI.

PI is found by typing Math. "dot", and then selecting PI.

If you move the mouse over PI and wait for the tool tip you will see the declaration of PI as (constant) double. (Double is a numeric type that includes decimal places.)

Experiment: Another constant is Math.E. Add another button to the program to display the value of E. (Note that System.Math.E is not the same as e that is the argument received by the procedure.)

The math functions most likely to be used by students learning C# are explained in more detail here.

Function Example Result Explanation
Abs Math.Abs(-3.87) 3.87 removes any minus sign
Sqrt Math.Sqrt(25) 5 square root
Round Math.Round(39.5) 40 rounds to nearest integer
Sign Math.Sign(-8) -1 returns 1 if positive, -1 if negative
Max Math.Max(54, 87) 87 returns larger of 2 values
Min Math.Min(54, 87) 54 returns smaller of 2 values
PI Math.PI 3.14159265358979 returns the constant PI
Pow Math.Pow(2, 3) 8 raises to power

Ceil (ceiling) and Floor

The ceil function finds the nearest whole number that is >= the argument. You can think of this as moving to the right on a number line.
Math.Ceiling(5.8) returns 6.
Math.Ceiling(-5.8) returns -5.

The floor function finds the nearest whole number that is <= the argument. You can think of this as moving to the left on a number line.
Math.Floor(5.8) returns 5.
Math.Floor(-5.8) returns -6.
ceil-floor

There are also trigonometric functions: Acos (cosine), Asin (sine) and exponential and logarithmic functions such as Exp (exponential). When you type Math. (dot) you can select from a pop-up list.

End of lesson, Next lesson: