0

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

我倾向于使用fmod类似:fmod(foo, 1.0)

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

我会不会有动力不简单地使用fmod?

4

1 回答 1

6

我能想到的两种方法,一个演员或四舍五入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 结果显示该fmod方法是迄今为止最慢的选项,而演员是最快的:QuickBench

于 2018-03-19T21:22:06.167 回答