C++ sqrt()

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

另请阅读

在我们结束之前,让我们来测试一下你对 C++ cmath sqrt() 的掌握程度!你能解决下面的挑战吗?

挑战

编写一个函数来查找数字的平方根。

  • 返回给定 num 的平方根。
  • 例如,如果 num = 25,则返回值应为 5
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战