+ 3

Square Root Function

How to define a square root function in c++. I know it is present in math.h header file. But I want to define it myself. Any ideas?

23rd Nov 2016, 11:54 AM
Megatron
Megatron - avatar
2 odpowiedzi
+ 3
#include <iostream> using namespace std; template<class T> double sqrt(T s) { T p; int i; double j,x; p=s; i=0; while(p!=0) { p=p/10; i++; } p=s; j=(double)(i*100); while(p!=0) { x=j; j=0.5*(j+s/j); if(x==j) return j; p=p-(p%2); } return j; } int main() { int i = 121; cout << sqrt(i); return 0; } Well it is not a efficient program but you can use it to find square root of any number(better on integers, but give you a rough value on float or double). Yes I know on line x==y is not a good condition for float or double variables. But I have show that you can use this rough code.
23rd Nov 2016, 1:50 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
You will have to write a custom function which does square root. This link refers to one of the method to get square root. http://www.math.com/school/subject1/lessons/S1U1L9DP.html it's easy, you can try that. But if you have your own method/algorithm you can implement that as well.
23rd Nov 2016, 12:05 PM
Nagendra Prajwal
Nagendra Prajwal - avatar