Home Communities
IT Knowledge
Inspiration
Languages
EN

C# / .NET - Math.Sqrt() method example

0 points
Created by:
260

`Math` `Sqrt` is a static method that returns a number which is the square root of input value. The method works only on positive real numbers.

``````using System;

public class Program
{
public static void Main(string[] args)
{
Console.WriteLine( Math.Sqrt(  4   ) ); //  2
Console.WriteLine( Math.Sqrt(  9   ) ); //  3

Console.WriteLine( Math.Sqrt(  2   ) ); //  1.4142135623730951
Console.WriteLine( Math.Sqrt(  0.5 ) ); //  0.7071067811865476
Console.WriteLine( Math.Sqrt(  0   ) ); //  0
Console.WriteLine( Math.Sqrt( -1   ) ); //  NaN
}
}``````

1. Documentation

 Syntax ``````namespace System { public static class Math { // ... public static double Sqrt(double number) { ... } // ... } }`````` Parameters `number` - double value in the range `0` to `+Infinity` (primitive value). Result Square root `number` value in range `0` to `+Infinity` (primitive value). If the operation can not be executed `NaN` is returned. Description `Sqrt` is a static method that returns a number which is square root of input value. The method works only on positive real numbers.

2. Square root with `Math.pow` method examples

In this example, the way how to calculate square root using power function is presented.

``````using System;

public class Program
{
static double CalculateSqrt(double value)
{
return Math.Pow(value, 0.5);
}

public static void Main(string[] args)
{
// Examples:
Console.WriteLine( CalculateSqrt(  4   ) ); //  2
Console.WriteLine( CalculateSqrt(  9   ) ); //  3

Console.WriteLine( CalculateSqrt(  2   ) ); //  1.4142135623730951
Console.WriteLine( CalculateSqrt(  0.5 ) ); //  0.7071067811865476
Console.WriteLine( CalculateSqrt(  0   ) ); //  0
Console.WriteLine( CalculateSqrt( -1   ) ); //  NaN
}
}``````
Join to our subscribers to be up to date with content, news and offers.