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.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(string[] args)
6
{
7
Console.WriteLine( Math.Sqrt( 4 ) ); // 2
8
Console.WriteLine( Math.Sqrt( 9 ) ); // 3
9
10
Console.WriteLine( Math.Sqrt( 2 ) ); // 1.4142135623730951
11
Console.WriteLine( Math.Sqrt( 0.5 ) ); // 0.7071067811865476
12
Console.WriteLine( Math.Sqrt( 0 ) ); // 0
13
Console.WriteLine( Math.Sqrt( -1 ) ); // NaN
14
}
15
}
Syntax |
xxxxxxxxxx 1 namespace System 2 { 3 public static class Math 4 { 5 // ... 6 public static double Sqrt(double number) { ... } 7 // ... 8 } 9 } |
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. |
In this example, the way how to calculate square root using power function is presented.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
static double CalculateSqrt(double value)
6
{
7
return Math.Pow(value, 0.5);
8
}
9
10
public static void Main(string[] args)
11
{
12
// Examples:
13
Console.WriteLine( CalculateSqrt( 4 ) ); // 2
14
Console.WriteLine( CalculateSqrt( 9 ) ); // 3
15
16
Console.WriteLine( CalculateSqrt( 2 ) ); // 1.4142135623730951
17
Console.WriteLine( CalculateSqrt( 0.5 ) ); // 0.7071067811865476
18
Console.WriteLine( CalculateSqrt( 0 ) ); // 0
19
Console.WriteLine( CalculateSqrt( -1 ) ); // NaN
20
}
21
}