sqrt() 的函数原型
double sqrt(double arg);
sqrt()
函数接受一个参数(double 类型)并返回其平方根(也为 double 类型)。
[Mathematics] √x = sqrt(x) [In C Programming]
sqrt()
函数定义在 math.h 头文件中。
要计算 int
、float
或 long 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