Possible Duplicate:
Rounding Number to 2 Decimal Places in C라운드
나는 C에서 here 같은 서명 double round(double d, int digits)
과 기능을 발견하지 않았습니다. 나는이 오류가 구축 할 때 :
error: too many arguments to function 'round'
가 어떻게 소수점 N 숫자와 C에서 반올림 할 수 있습니까?
Possible Duplicate:
Rounding Number to 2 Decimal Places in C라운드
나는 C에서 here 같은 서명 double round(double d, int digits)
과 기능을 발견하지 않았습니다. 나는이 오류가 구축 할 때 :
error: too many arguments to function 'round'
가 어떻게 소수점 N 숫자와 C에서 반올림 할 수 있습니까?
#include <math.h>
double my_round(double x, unsigned int digits) {
if (digits > 0) {
return my_round(x*10.0, digits-1)/10.0;
}
else {
return round(x);
}
}
다소 빠를 가능성이 방법 (숫자의 일부 값에 대한 느린 될 것입니다) 재귀를 사용하지만, 느린 pow
기능에 단일 통화에 의존하는 :
#include <math.h>
double my_round(double x, unsigned int digits) {
double fac = pow(10, digits);
return round(x*fac)/fac;
}
더 빠른 방법은 가능성이있는 룩업 테이블을 사전 계산하여 pow
대신 사용하는 것입니다. "answerd"하다니
#include <math.h>
double fac[]; // population of this is left as an exercise for the reader
double my_round(double x, unsigned int digits) {
return round(x*fac[digits])/fac[digits];
}
왜 downvote? – andand
이것은 실제로 C로 컴파일되지 않는다고 추측하고 있지만 C++로합니다. –
간단한 산술로 충분할 재귀를 사용 하시겠습니까? –
A (매우) 간단한 기능이있어, C 표준에서
double round1(double num, int N) {
int temp=(int) num*pow(10,N);
double roundedN= temp/pow(10,N);
return roundedN;
}
, 이러한 기능은 존재하지 않습니다. 어쨌든, 당신은 당신 자신의 것을 쓸 수 있습니다.
#include <math.h>
/* Round `n` with `c` digits after decimal point. */
double nround (double n, unsigned int c)
{
double marge = pow (10, c);
double up = n * marge;
double ret = round (up)/marge;
return ret;
}
는 참조 의견 포인트를 "소수점"부동에 대한 위.
, 여기 괜찮은 해답을주는 임의의 큰 번호를 작동 하나 : 물론
double round1(double num, int N) {
ASSERT(N > 0);
double p10 = pow(10,N);
return round(num* p10)/p10;
}
, 언급 한 바와 같이, 부동 소수점 숫자는 소수점 일련의 번호가없는 숫자이며, 예를 들어 printf("%8.5f", round1(3.7519, 1));
을 호출하면 PRINT를 3.70000으로 보장 할 수 없습니다.
'sprintf'가 있습니다. – melpomene
@melpomene, 감사합니다 http://stackoverflow.com/questions/994764/rounding-doubles-5-sprintf 찾았지만 반환 값을 얻을 필요가뿐만 아니라 그것을 인쇄하십시오. – testCoder
소수점 표시 관련합니다. 하나는 가장 가까운 부정적인 힘을 10으로 돌릴 수 있습니다 -하지만 왜 그런 것을 원하겠습니까? –