Finding square root of a number without using Math.Sqrt Method in C# Console Application
You may also like:
Calculate Square Root Without Using Math.Sqrt in C#
Calculate Square Root Without Using Sqrt in C
First one, we have to know how to calculate square root without using a function. For calculate square root of a number, we will use The Babylonian Method for Computing Square Roots
Calculate Square Root without Math.Sqrt Method In C# Console (Only int type)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | static void Main(string[] args) { Console.Write("Enter a number:"); int number = Convert.ToInt32(Console.ReadLine()); double root = 1; int i = 0; //The Babylonian Method for Computing Square Roots while (true) { i = i + 1; root = (number / root + root) / 2; if (i == number + 1) { break; } } //Output Console.WriteLine("Square root:{0}",root); Console.ReadLine(); } |
Alternative Way: (All number types and if you want to calculate square root with decimal type you should convert double to decimal)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Program { static void Main(string[] args) { Console.Write("Enter a number:"); double number = Convert.ToDouble(Console.ReadLine()); if (number > 0) { double root = number / 3; int i; for (i = 0; i < 32; i++) root = (root + number / root) / 2; Console.WriteLine("Square root:{0}", root); } else { Console.WriteLine(Double.NaN); } Console.ReadLine(); } } |
Output:
Calculate Square Root without Math.Sqrt Method In C# Windows Form
Calculate Button Click Event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | private void btnCalc_Click(object sender, EventArgs e) { int number = Convert.ToInt32(txtNumber.Text); double root = 1; int i = 0; //The Babylonian Method for Computing Square Roots while (true) { i = i + 1; root = (number / root + root) / 2; if (i == number + 1) { break; } } lbResult.Text = root.ToString(); } |
OutOut
Square root c# without sqrt ,program to find square root of a number without using inbuilt function,