๐ŸŽ“ A1Learner
๐Ÿ”

C# Math

The Math class is a built-in class that holds ready-made maths methods. Its methods cover jobs like finding the larger value and rounding a number.

Largest and smallest

Math.Max picks the larger value. Math.Min picks the smaller value.

using System;

class Program
{
    static void Main(string[] args)
    {
        int x = 5;
        int y = 9;
        Console.WriteLine(Math.Max(x, y));
        Console.WriteLine(Math.Min(x, y));
    }
}

Roots and powers

Math.Sqrt finds a square root. Math.Pow raises a number to a power.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Math.Sqrt(16));
        Console.WriteLine(Math.Pow(2, 3));
    }
}

Rounding three ways

Round goes to the nearest whole number. Floor goes down and Ceiling goes up.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Math.Round(9.99));
        Console.WriteLine(Math.Round(9.49));
        Console.WriteLine(Math.Floor(9.99));
        Console.WriteLine(Math.Ceiling(9.49));
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        int a = 3;
        int b = 4;
        double c = Math.Sqrt(a * a + b * b);
        Console.WriteLine("Hypotenuse: " + c);
    }
}

Key points

  • Math.Max returns the larger of two values.
  • Math.Min returns the smaller of two values.
  • Math.Sqrt returns the square root of a number.
  • Math.Pow raises the first number to the power of the second.
  • Math.Round rounds a number to the nearest whole number.
  • Math.Floor rounds a number down to a whole number.
  • Math.Ceiling rounds a number up to a whole number.

In this example, a is 3 and b is 4. The squares are 9 and 16. Their sum is 25. Math.Sqrt gives 5 for that sum. The printed line is "Hypotenuse: 5".

Note

Math methods return double values, and a whole double prints without a decimal point.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does Console.WriteLine(Math.Sqrt(25)); print?