Monday, 26 February 2018

Write a program for square root


Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SquareRootProgramWithoutUsingInBuiltSQRTMethod
{
    class Program
    {
        public static float FindSquareRoot_BS(int number)
        {
            float result = 0;
            float diff = 0;
            float minDiff = Math.Abs(result * result - number);
            int count = 0;
            float tempResult = 0;
            while (true)
            {
                tempResult = Convert.ToSingle(count) / 1000;
                diff = Math.Abs(tempResult * tempResult - number);
                if (diff <= minDiff)
                {
                    minDiff = diff;
                    result = tempResult;
                }
                else
                    return result;
                count++;
            }
        }

        static void Main(string[] args)
        {
           float returnValue = FindSquareRoot_BS(36); // pass number whose square root is find out
            Console.Write(returnValue);
            Console.ReadLine();
        }
    }
}

output: 6

No comments:

Post a Comment