获取数字小数部分的最佳方法
Best way to get the Fractional Part of a Number
鉴于const auto foo = 13.42
我想得到数字的小数部分,所以.42
我倾向于只使用这样的fmod
:fmod(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
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?