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 
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.