sqrt()函数以及C ++中的示例
C++sqrt()函数
sqrt()函数是cmath标头(在早期版本中为<math.h>)的库函数,用于查找给定数字的平方根,它接受数字并返回平方根。
注意:如果我们提供负值,则sqrt()函数将返回域错误。(-nan)。
sqrt()函数语法:
sqrt(x);
参数:x-要计算其平方根的数字。
返回值:double-它返回double值,它是给定数字x的平方根。
示例
Input:
int x = 2;
Function call:
sqrt(x);
Output:
1.41421C++代码演示sqrt()函数示例
//示例
//sqrt()功能
#include <iostream>
#include <cmath>
using namespace std;
//主代码部分
int main(){
float x;
//输入值
cout<<"Enter a number: ";
cin>>x;
//计算平方根
float result = sqrt(x);
cout<<"square root of "<<x<<" is = "<<result;
cout<<endl;
return 0;
}输出结果
First run: Enter a number: 4 square root of 4 is = 2 Second run: Enter a number: 10.234 square root of 10.234 is = 3.19906 Third run: Enter a number: 0 square root of 0 is = 0 Fourth run: Enter a number: -10 square root of -10 is = -nan