Open In App

C# | Math.Sqrt() Method

In C#, Math.Sqrt() is a Math class method which is used to calculate the square root of the specified number. Sqrt is a slower computation. It can be cached for a performance boost. Syntax:

public static double Sqrt(double d)

Parameter:



d: Number whose square root is to be calculated and type of this parameter is System.Double.

Return Type: This method returns the square root of d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The return type of this method is System.Double. Examples:



Input  : Math.Sqrt(81) 
Output : 9

Input  : Math.Sqrt(-81) 
Output : NaN

Input  : Math.Sqrt(0.09) 
Output : 0.3

Input  : Math.Sqrt(0)
Output : 0

Input  : Math.Sqrt(-0)
Output : 0

Below C# programs illustrate the working of Math.Sqrt():




// C# program to illustrate the
// Math.Sqrt() method
using System;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        double x = 81;
 
        // Input positive value, Output square root of x
        Console.Write(Math.Sqrt(x));
    }
}

Output:
9




// C# program to illustrate the Math.Sqrt()
// method when the argument is Negative
using System;
 
class GFG {
 
    // Main method
    public static void Main()
    {
        double x = -81;
 
        // Input Negative value, Output square root of x
        Console.Write(Math.Sqrt(x));
    }
}

Output:
NaN




// C# program to illustrate the Math.Sqrt()
// method when the argument is double value
// with decimal places
using System;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        double x = 0.09;
 
        // Input value with decimal places,
        // Output square root of x
        Console.Write(Math.Sqrt(x));
    }
}

Output:
0.3




// C# program to illustrate the Math.Sqrt()
// method when the argument is positive
// or negative Zero
using System;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        double x = 0;
 
        // Input value positive Zero, Output
        // square root of x
        Console.WriteLine(Math.Sqrt(x));
        double y = -0;
 
        // Input value Negative Zero,
        // Output square root of y
        Console.Write(Math.Sqrt(y));
    }
}

Output:
0
0

Note: If the value is too large then it gives the compile time error as error CS1021: Integral constant is too large. Reference: https://msdn.microsoft.com/en-us/library/system.math.sqrt


Article Tags :
C#