获取数字小数部分的最佳方法

Best way to get the Fractional Part of a Number

本文关键字:最佳 方法 数字 小数部 获取      更新时间:2023-10-16

鉴于const auto foo = 13.42我想得到数字的小数部分,所以.42

我倾向于只使用这样的fmodfmod(foo, 1.0)

但我也可以做foo / static_cast<int>(foo) - 1.0或者其他神秘的方法。

我有没有动力不简单地使用fmod

我能想到的两种方法,要么是演员表,要么是四舍五入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;
}

快速工作台结果显示fmod方法是迄今为止最慢的选项,而演员表是最快的选项:QuickBench