How is the sqrt function used in C++?
In C++, the sqrt() function is used to calculate the square root of a given number. Its syntax is as follows:
#include<cmath>
...
double sqrt(double x);
float sqrt(float x);
long double sqrt(long double x);
The sqrt() function takes one parameter x, which indicates the number to calculate the square root of. It returns a value of type double, representing the square root of x.
To use this function, you need to include the cmath header file. Here is an example:
#include<iostream>
#include<cmath>
int main() {
double num = 16.0;
double result = sqrt(num);
std::cout << "平方根为: " << result << std::endl;
return 0;
}
The output is: the square root is 4.0.
Please note that the sqrt() function is a mathematical function, so the result it returns is a floating point number. If an integer result is needed, it can be converted to an integer type.