IT/C C++

[C/C++] math.h로 정확한 파이값 사용하는 방법

크몽 '경매하는 개발자' 님의 경매/부동산/IT/사업 채널 2023. 5. 25. 21:24
반응형

[C/C++] math.h로 정확한 파이값 사용하는 방법

반응형

 


엄밀히 이야기해서 정확한 파이값은 아니고, double 형으로 표현되는 마지막 자리까지의 파이값이다.

그래도 우리가 정의하는 '#define pi 3.141592'와 같은 방식보다는 훨씬 정확하니 필자는 사용을 권장한다.

 

Math.h로 정의되는 상수값의 종류는 아래와 같다.

반응형

 

 

/** The constant \a e.	*/
#define M_E		2.7182818284590452354

/** The logarithm of the \a e to base 2. */
#define M_LOG2E		1.4426950408889634074	/* log_2 e */

/** The logarithm of the \a e to base 10. */
#define M_LOG10E	0.43429448190325182765	/* log_10 e */

/** The natural logarithm of the 2.	*/
#define M_LN2		0.69314718055994530942	/* log_e 2 */

/** The natural logarithm of the 10.	*/
#define M_LN10		2.30258509299404568402	/* log_e 10 */

/** The constant \a pi.	*/
#define M_PI		3.14159265358979323846	/* pi */

/** The constant \a pi/2.	*/
#define M_PI_2		1.57079632679489661923	/* pi/2 */

/** The constant \a pi/4.	*/
#define M_PI_4		0.78539816339744830962	/* pi/4 */

/** The constant \a 1/pi.	*/
#define M_1_PI		0.31830988618379067154	/* 1/pi */

/** The constant \a 2/pi.	*/
#define M_2_PI		0.63661977236758134308	/* 2/pi */

/** The constant \a 2/sqrt(pi).	*/
#define M_2_SQRTPI	1.12837916709551257390	/* 2/sqrt(pi) */

/** The square root of 2.	*/
#define M_SQRT2		1.41421356237309504880	/* sqrt(2) */

/** The constant \a 1/sqrt(2).	*/
#define M_SQRT1_2	0.70710678118654752440	/* 1/sqrt(2) */

/** NAN constant.	*/
#define NAN	__builtin_nan("")

/** INFINITY constant.	*/
#define INFINITY	__builtin_inf()
반응형

 

 

헤더 정의부에 아래와 같이 입력하면 사용이 가능하다.

 

#define _USE_MATH_DEFINES
#include <math.h>

 

 

예시)

#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>

//반지름을 입력받아 원의 넓이와 둘레 구하기

int main(){
	int r;
    
    printf("r : ");
    scanf("%d", &r);
    
    printf("원의 넓이 : %.2lf \n", M_PI*r*r);
    printf("원의 둘레 : %.2lf \n", 2*M_PI*r);
    
    return 0;
}
반응형

 

파이(M_PI)말고도 위에 표시된 종류들을 참고하여 다른 정의된 상수값을 사용할 수 있다.

반응형