how to make a square root function in c++ without stl code example
Example 1: square root c++
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(){
float num, raiz;
printf("enter a number: \t");
scanf("%f",&num);
raiz = sqrt(num);
printf("The square root of %f is: %f.\n", num, raiz);
system("pause");
return 0;
}
Example 2: how to make a square root function in c++ without stl
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0;
while(fabs(num - (temp * temp)) > SOME_SMALL_VALUE)
{
temp = (lower_bound+upper_bound)/2;
if (temp*temp >= num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
}
return temp;
}
Example 3: how to make a square root function in c++ without stl
double sqrt(double number)
{
double error = 0.00001;
double s = number;
while ((s - number / s) > error)
{
s = (s + number / s) / 2;
}
return s;
}
Example 4: how to make a square root function in c++ without stl
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0;
int exp = 0;
x = frexp(x, &exp);
if (exp & 1) {
exp--;
x *= 2;
}
double y = (1+x)/2;
double z = 0;
while (y != z) {
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2);
}
Example 5: how to make a square root function in c++ without stl
#include <iostream>
using namespace std;
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0;
int nCount = 50;
while(nCount != 0)
{
temp=(lower_bound+upper_bound)/2;
if(temp*temp==num)
{
return temp;
}
else if(temp*temp > num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
nCount--;
}
return temp;
}
int main()
{
double num;
cout<<"Enter the number\n";
cin>>num;
if(num < 0)
{
cout<<"Error: Negative number!";
return 0;
}
cout<<"Square roots are: +"<<sqrtnum(num) and <<" and -"<<sqrtnum(num);
return 0;
}