[英]Best way to get the Fractional Part of a Number
Given const auto foo = 13.42
I would like to get the numbers fractional part, so .42 给定const auto foo = 13.42
我想获取数字的小数部分,因此.42
I'm leaning toward just using fmod
like: fmod(foo, 1.0)
我倾向于仅使用fmod
: fmod(foo, 1.0)
But I could also just do foo / static_cast<int>(foo) - 1.0
Or perhaps some other mystical method. 但是我也可以只做foo / static_cast<int>(foo) - 1.0
或其他一些神秘的方法。
Would there be a motivation for me to not simply use fmod
? 我有动力不仅仅使用fmod
吗?
Two ways I can think of, either a cast or rounding down with std::floor
我可以想到两种方式,无论是强制转换还是使用std::floor
舍入
int main()
{
const auto foo = 13.53;
auto firstWay = foo - static_cast<long long>(foo); // Truncating via cast and subtracting
auto otherWay = foo - std::floor(foo); // Rounding down and subtracting
return 0;
}
Quick Bench Result shows the fmod
approach as the slowest option by far, and the cast as the fastest: QuickBench 快速基准测试结果显示fmod
方法是迄今为止最慢的选项,而强制转换则是最快的: QuickBench
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.