Write code in c++ for calculating square root

Here is an example of a function in C++ that calculates the square root of a given number using the Newton-Raphson method:



#include <cmath>

double square_root(double x) {
    double root = x;
    double precision = 0.00001;
    while (fabs(root * root - x) > precision) {
        root = (root + x / root) / 2;
    }
    return root;
}


Note: The above code uses the fabs function from the cmath library which returns the absolute value of a float or double. This function is used to compare the square of the approximation to the original number and check if the approximation is accurate enough.

OR

#include <cmath>
#include <iostream>

int main() {
    double num;
    std::cout << "Enter a number: ";
    std::cin >> num;
    double sqrt_num = sqrt(num);
    std::cout << "The square root of " << num << " is " << sqrt_num << std::endl;
    return 0;
}

This code takes a user input and uses the sqrt() function from the cmath library to calculate the square root of the input. The result is then printed to the console.
Note: The sqrt() function in cmath library is for floating-point numbers. If you want to calculate the square root for integers, you can use the sqrt() function from math.h or you can use the newton-raphson method to calculate square root of any number.

Comments