c++ sqrt


std::sqrt, std::sqrtf, std::sqrtl

定義於頭文件  <cmath>
   
  (1)  
float       sqrt float arg );
 
float       sqrtffloat arg );
(C++11 起)
double      sqrt double arg );
(2)  
  (3)  
long double sqrt long double arg );
 
long double sqrtllong double arg );
(C++11 起)
double      sqrt ( IntegralType arg );
(4) (C++11 起)
     
1-3) 計算 arg 的平方根。
4) 接受任何整數類型參數的重載集或函數模模板。等價於 (2) (將參數轉型為 double )。

參數

arg - 浮點或整數類型

返回值

若不出現錯誤,則返回 arg 的平方根( argarg )。

若出現定義域錯誤,則返回實現定義值(支持的平台上為 NaN )。

若出現下溢所致的值域錯誤,則返回(舍入后的)正確結果。

錯誤處理

報告 math_errhandling 中指定的錯誤。

若 arg 小於零則出現定義域錯誤。

若實現支持 IEEE 浮點算術( IEC 60559 ),則

  • 若參數小於 -0 ,則引發 FE_INVALID 並返回 NaN 。
  • 若參數為 +∞ 或 ±0 ,則返回不修改的參數。
  • 若參數為 NaN ,則返回 NaN 。

注解

IEEE 標准要求 std::sqrt 為准確。其他要求為准確的運算只有算術運算符和函數 std::fma 。舍入到返回類型后(用默認舍入模式), std::sqrt 的結果與無限精度結果不可辨別。換言之,誤差小於 0.5 ulp 。其他函數,含 std::pow ,不受這種制約。

示例

#include <iostream>
#include <cmath> #include <cerrno> #include <cfenv> #include <cstring>   #pragma STDC FENV_ACCESS ON   int main() { // 正常使用 std::cout << "sqrt(100) = " << std::sqrt(100) << '\n' << "sqrt(2) = " << std::sqrt(2) << '\n' << "golden ratio = " << (1+std::sqrt(5))/2 << '\n'; // 特殊值 std::cout << "sqrt(-0) = " << std::sqrt(-0.0) << '\n'; // 錯誤處理 errno = 0; std::feclearexcept(FE_ALL_EXCEPT); std::cout << "sqrt(-1.0) = " << std::sqrt(-1) << '\n'; if(errno == EDOM) std::cout << " errno = EDOM " << std::strerror(errno) << '\n'; if(std::fetestexcept(FE_INVALID)) std::cout << " FE_INVALID raised\n"; }

可能的輸出:

sqrt(100) = 10
sqrt(2) = 1.41421
golden ratio = 1.61803
sqrt(-0) = -0
sqrt(-1.0) = -nan
    errno = EDOM Numerical argument out of domain
    FE_INVALID raised

參閱

(C++11)(C++11)
求某數的給定次冪( xyxy )
(函數)
(C++11)(C++11)(C++11)
計算立方根( 3xx3 )
(函數)
(C++11)(C++11)(C++11)
計算兩個給定數的平方和的平方根( x2+y2x2+y2 )
(函數)
右半平面范圍中的復平方根
(函數模板)
應用函數 std::sqrt 到 valarray 的每個元素
(函數模板)
sqrt 的 C 文檔


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM