C sqrt()

sqrt() 的函数原型

double sqrt(double arg);

sqrt() 函数接受一个参数(double 类型)并返回其平方根(也为 double 类型)。

[Mathematics]  √x = sqrt(x) [In C Programming]

sqrt() 函数定义在 math.h 头文件中。


要计算 intfloatlong double 数据类型的平方根,您可以使用类型转换运算符显式将其转换为 double

int x = 0;
double result;
result = sqrt(double(x));

您还可以使用 sqrtf() 函数专门处理 float 类型,使用 sqrtl() 处理 long double 类型。

long double sqrtl(long double arg );
float sqrtf(float arg );

示例:C sqrt() 函数

#include <math.h>
#include <stdio.h>

int main() {
   double number, squareRoot;

   printf("Enter a number: ");
   scanf("%lf", &number);

   // computing the square root
   squareRoot = sqrt(number);

   printf("Square root of %.2lf =  %.2lf", number, squareRoot);

   return 0;
}

输出

Enter a number: 23.4
Square root of 23.40 =  4.84
你觉得这篇文章有帮助吗?

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

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

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