C++ sqrt() 函數
sqrt() 函數是 cmath 頭文件(早期版本為<math.h>)的庫函數,用於求給定數字的平方根,它接受一個數字並返回平方根。
注意:如果我們提供負值,sqrt() 函數將返回域錯誤。 (-nan
)。
sqrt() 函數的語法:
sqrt(x);
參數: x
– 要計算其平方根的數字。
返回值: double
– 它返回雙精度值,即給定數字的平方根x
。
例:
Input: int x = 2; Function call: sqrt(x); Output: 1.41421
C++代碼演示sqrt()函數的例子
// C++ code to demonstrate the example of
// sqrt() function
#include <iostream>
#include <cmath>
using namespace std;
// main code section
int main()
{
float x;
//input the value
cout<<"Enter a number:";
cin>>x;
// calculate the square root
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
相關用法
- C++ complex sqrt()用法及代碼示例
- C++ std::max()用法及代碼示例
- C++ std::string::push_back()用法及代碼示例
- C++ std::less_equal用法及代碼示例
- C++ set rbegin()用法及代碼示例
- C++ string::length()用法及代碼示例
- C++ set upper_bound()用法及代碼示例
- C++ std::is_member_object_pointer模板用法及代碼示例
- C++ std::copy_n()用法及代碼示例
- C++ std::string::insert()用法及代碼示例
- C++ std::is_sorted_until用法及代碼示例
- C++ std::iota用法及代碼示例
- C++ std::numeric_limits::digits用法及代碼示例
- C++ std::string::data()用法及代碼示例
- C++ smatch max_size()用法及代碼示例
- C++ std::is_permutation用法及代碼示例
- C++ std::list::sort用法及代碼示例
- C++ string::npos用法及代碼示例
- C++ set swap()用法及代碼示例
- C++ std::all_of()用法及代碼示例
注:本文由純淨天空篩選整理自 sqrt() function with example in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。