C# Tutorial C# Advanced C# References

C# Math - Sqrt() Method



The C# Sqrt() method returns the square root of the given number. In special cases it returns the following:

  • If the argument is NaN or less than zero, then method returns NaN.
  • If the argument is positive infinity, the method returns the same as the argument.

Syntax

public static float Sqrt (float arg);

Parameters

arg Specify the number whose square root to be found.

Return Value

Returns the square root of the specified number.

Example:

In the example below, Sqrt() method is used to find out the square root of the given number.

using System;

class MyProgram {
  static void Main(string[] args) {
    Console.WriteLine("Math.Sqrt(64) = "
                      + Math.Sqrt(64));
    Console.WriteLine("Math.Sqrt(500) = "
                      + Math.Sqrt(500));
    Console.WriteLine("Math.Sqrt(-500) = "
                      + Math.Sqrt(-500));
    Console.WriteLine("Math.Sqrt(Double.NaN) = "
                      + Math.Sqrt(Double.NaN));
    Console.WriteLine("Math.Sqrt(Double.NegativeInfinity) = "
                      + Math.Sqrt(Double.NegativeInfinity));
    Console.WriteLine("Math.Sqrt(Double.PositiveInfinity) = "
                      + Math.Sqrt(Double.PositiveInfinity));
  }
}

The output of the above code will be:

Math.Sqrt(64) = 8
Math.Sqrt(500) = 22.3606797749979
Math.Sqrt(-500) = NaN
Math.Sqrt(Double.NaN) = NaN
Math.Sqrt(Double.NegativeInfinity) = NaN
Math.Sqrt(Double.PositiveInfinity) = Infinity

❮ C# Math Methods

5