Home » C++ programming language

sqrt() function with example in C++

C++ sqrt() function: Here, we are going to learn about the sqrt() function with example of cmath header in C++ programming language?
Submitted by IncludeHelp, on April 26, 2019

C++ sqrt() function

sqrt() function is a library function of cmath header (<math.h> in earlier versions), it is used to find the square root of a given number, it accepts a number and returns the square root.

Note: If we provide a negative value, sqrt() function returns a domain error. (-nan).

Syntax of sqrt() function:

    sqrt(x);

Parameter(s): x – a number whose square root to be calculated.

Return value: double – it returns double value that is the square root of the given number x.

Example:

    Input:
    int x = 2;

    Function call:
    sqrt(x);

    Output:
    1.41421

C++ code to demonstrate the example of sqrt() function

// C++ code to demonstrate the example of 
// sqrt() function

#include <iostream>
#include <cmath>
using namespace std;

// main code section
int main()
{
    float x;
    
    //input the value
    cout<<"Enter a number: ";
    cin>>x;

    // calculate the square root
    float result = sqrt(x);
    cout<<"square root of "<<x<<" is = "<<result;
    cout<<endl;
    
    return 0;
}

Output

First run:
Enter a number: 4
square root of 4 is = 2 

Second run:
Enter a number: 10.234 
square root of 10.234 is = 3.19906

Third run:
Enter a number: 0
square root of 0 is = 0

Fourth run:
Enter a number: -10
square root of -10 is = -nan 


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.