EN
C# / .NET - Math.Sqrt() method example
0
points
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 |
|
Parameters | number - double value in the range 0 to +Infinity (primitive value). |
Result |
Square root If the operation can not be executed |
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
}
}