[英]Round double to nearest uint64_t
我需要將 double 舍入到最接近的有效uint64_t
。
所以
uint64_t Round(double);
Round(std::numeric_limits<double>::max())==std::numeric_limits<uint64_t>::max();
Round(std::numeric_limits<double>::lowest())==std::numeric_limits<uint64_t>::min();
Round(1.1)==1;
Round 應該等同於但對於 uint64_t 而不是有符號積分
auto Round(double d){
std::fesetround(FE_TONEAREST);
return llrint(d);
}
std && boost 中是否有任何函數可以啟用此功能?
double
不能保存uint64_t
所有值,因為兩者通常都是 64 位,並且double
需要為指數留出位。
但是,獲得最接近的值並不難:
uint64_t Round(double x){
double rounded=round(x);
if(rounded<0)
return 0;
if(rounded>=pow(2,64))
return std::numeric_limits<uint64_t>::max();
return static_cast<uint64_t>(rounded);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.