본문 바로가기

Programming/c

C로 소숫점 반올림하기


아래의 소스를 참조합니다.

반올림 하는 매크로를 작성하여 사용합니다. 

#include <math.h>를 하는 것을 잊지 맙시다.

예 : RoundOff.c

/*

 * RoundOff.c

 *  Created on: 2012. 4. 10.

 *      Author: Lee Hyun Jung

 */

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

/**

 * num : 반올림할 대상 

 * point : 반올림할 자릿수

 */

#define roundOff(num, point) ((floor((x)* (pow(10, point)) + 0.5)/ (pow(10, point))))


int main() {

double x = 12345.67847897;


int i;


for(i=2; i<8; i++){

printf("%f의 %d자리 반올림=%f\n", x, i, roundOff(x, i));

}

return EXIT_SUCCESS;

}

실행결과 :

12345.678479의 2자리 반올림=12345.680000

12345.678479의 3자리 반올림=12345.678000

12345.678479의 4자리 반올림=12345.678500

12345.678479의 5자리 반올림=12345.678480

12345.678479의 6자리 반올림=12345.678479

12345.678479의 7자리 반올림=12345.678479

출처 : 김상형님의 [혼자서 연구하며 배우는 C / C++ ]

'Programming > c' 카테고리의 다른 글

c언어를 공부하자.  (0) 2011.06.16