CPP_DEC_FLOAT을 둥글게하십시오
-
21-12-2019 - |
문제
.str(n, std::ios_base::scientific)
를 사용하여 ccp_dec_float
s를 인쇄하고 있습니다.
그것은 그것이 라운드를 알아 차렸다.
회계를 위해 cpp_dec_float
를 사용하고 있으므로 아래쪽으로 반올림해야합니다.어떻게이 작업을 수행 할 수 있습니까?
해결책
그것은 반올림되지 않습니다.실제로 은행가의 라운드 : coliru에 라이브
#include <boost/multiprecision/number.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
namespace mp = boost::multiprecision;
int main()
{
using Dec = mp::cpp_dec_float_50;
for (Dec d : {
Dec( "3.34"), Dec( "3.35"), Dec( "3.38"),
Dec( "2.24"), Dec( "2.25"), Dec( "2.28"),
Dec("-2.24"), Dec("-2.25"), Dec("-2.28"),
Dec("-3.34"), Dec("-3.35"), Dec("-3.38"),
})
{
std::cout << d.str(2, std::ios_base::fixed)
<< " -> " << d.str(1, std::ios_base::fixed) << "\n";
}
}
.
인쇄물 :
3.34 -> 3.3
3.35 -> 3.4
3.38 -> 3.4
2.24 -> 2.2
2.25 -> 2.2
2.28 -> 2.3
-2.24 -> -2.2
-2.25 -> -2.2
-2.28 -> -2.3
-3.34 -> -3.3
-3.35 -> -3.4
-3.38 -> -3.4
.
그래서 다른 종류의 반올림을 원한다면 명시 적으로
를 쓰고 싶습니다.여기는 일반적인 접근 방식 ( collu 라이브)
template <int decimals = 0, typename T>
T round_towards_zero(T const& v)
{
static const T scale = pow(T(10), decimals);
if (v.is_zero())
return v;
// ceil/floor is found via ADL and uses expression templates for optimization
if (v<0)
return ceil(v*scale)/scale;
else
// floor is found via ADL and uses expression templates for optimization
return floor(v*scale)/scale;
}
.
은 정적으로 알려진 스케일 팩터로 인해 최적의 코드로 적어 표현식 템플리트 의 사용을 희망적으로 컴파일합니다.
다른 팁
당신이 특정 소수점으로 반올림하려고하는 것으로 가정하고, 정확합니까?
표준 반올림
double rounding_func(double in, double precision){
return round(in*pow(10,precision))/pow(10,precision);
}
.
그러나 귀하의 제목이 말한 것처럼, 당신은 그것을 둥글게하려고 노력하고 있으므로
를 고려하십시오.double rounding_func(double in, double precision){
return floor(in*pow(10,precision))/pow(10,precision);
}
.
행운을 빕니다!
제휴하지 않습니다 StackOverflow