如何在C ++中使用PI常量

我想在一些C ++程序中使用PI常量和三角函數。 我獲得了include <math.h>的三角函數。 可是,此頭文件中彷佛沒有PI的定義。 緩存

如何在不手動定義PI的狀況下獲取PI? ide


#1樓

math.hPosix手冊頁函數

The  <math.h>  header  shall  provide for the following constants.  The
   values are of type double and are accurate within the precision of  the
   double type.

   M_PI   Value of pi

   M_PI_2 Value of pi/2

   M_PI_4 Value of pi/4

   M_1_PI Value of 1/pi

   M_2_PI Value of 2/pi

   M_2_SQRTPI
          Value of 2/ sqrt pi

#2樓

Pi能夠按atan(1)*4 。 你能夠用這種方式計算值並緩存它。 spa


#3樓

標準C ++沒有PI的常量。 code

許多C ++編譯器定義M_PIcmath (或在math.h爲C)做爲非標準擴展。 您可能必須先#define _USE_MATH_DEFINES才能看到它。 ci


#4樓

在某些(特別是較舊的)平臺上(請參閱下面的評論),您可能須要這樣作 get

#define _USE_MATH_DEFINES

而後包含必要的頭文件: 編譯器

#include <math.h>

pi的值能夠經過如下方式訪問: 數學

M_PI

在個人math.h (2014)中,它被定義爲: it

# define M_PI           3.14159265358979323846  /* pi */

但請查看math.h瞭解更多信息。 來自「舊」 math.h的摘錄(2009年):

/* Define _USE_MATH_DEFINES before including math.h to expose these macro
 * definitions for common math constants.  These are placed under an #ifdef
 * since these commonly-defined names are not part of the C/C++ standards.
 */

然而:

  1. 在較新的平臺上(至少在個人64位Ubuntu 14.04上)我不須要定義_USE_MATH_DEFINES

  2. 在(最近的)Linux平臺上,做爲GNU擴展提供了long double值:

    # define M_PIl 3.141592653589793238462643383279502884L /* pi */

#5樓

因爲官方標準庫沒有定義常量PI,所以您必須本身定義它。 因此你的問題的答案是「如何在不手動定義PI的狀況下得到PI?」 是「你沒有 - 或者你依賴於一些特定於編譯器的擴展。」 若是您不關心可移植性,能夠查看編譯器的手冊。

C ++容許你寫

const double PI = std::atan(1.0)*4;

可是這個常量的初始化並不保證是靜態的。 然而,G ++編譯器將這些數學函數做爲內在函數處理,而且可以在編譯時計算此常量表達式。

相關文章
相關標籤/搜索