C++ 中的 sqrt()
函数返回一个数字的平方根。此函数定义在 cmath 头文件中。
在数学上,sqrt(x) = √x
。
示例
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << "Square root of 25 = ";
// print the square root of 25
cout << sqrt(25);
return 0;
}
// Output: Square root of 25 = 5
sqrt() 语法
sqrt()
函数的语法是
sqrt(double num);
sqrt() 参数
sqrt()
函数接受以下参数
- num - 一个非负数,用于计算其平方根
注意: 如果将负参数传递给 sqrt()
,则会发生域错误。
sqrt() 返回值
sqrt()
函数返回
- 给定参数的平方根
sqrt() 声明
sqrt()
在 cmath 头文件中定义的声明如下
double sqrt(double x);
float sqrt(float x);
long double sqrt(long double x);
// for integral type
double sqrt(T x);
示例 1:C++ sqrt()
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double num = 10.25;
double result = sqrt(num);
cout << "Square root of " << num << " is " << result;
return 0;
}
输出
Square root of 10.25 is 3.20156
示例 2:带整数参数的 sqrt() 函数
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long num = 464453422;
double result = sqrt(num);
cout << "Square root of " << num << " is " << result;
return 0;
}
输出
Square root of 464453422 is 21551.2
另请阅读