Most efficient/elegant way to clip a number?(剪辑数字的最有效/优雅的方法?)
问题描述
给定一个实数 (n),这个实数可以是的最大值(上),以及这个实数可以是的最小值(下),我们如何最有效地裁剪 n,使其保持在下限和上限之间?
Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lower and upper?
当然,使用一堆 if 语句可以做到这一点,但这很无聊!更紧凑、优雅/有趣的解决方案怎么样?
Of course, using a bunch of if statements can do this, but that's boring! What about more compact and elegant/fun solutions?
我自己的快速尝试(C/C++):
My own quick attempt (C/C++):
float clip( float n, float lower, float upper )
{
n = ( n > lower ) * n + !( n > lower ) * lower;
return ( n < upper ) * n + !( n < upper ) * upper;
}
我确信还有其他更好的方法可以做到这一点,这就是我将它放在那里的原因..!
I'm sure there are other, better ways to do this, that's why I'm putting this out there..!
推荐答案
乏味、陈旧、可读和最短的又如何:
What about boring, old, readable, and shortest yet:
float clip(float n, float lower, float upper) {
return std::max(lower, std::min(n, upper));
}
?
这个表达式也可以像这样泛化":
This expression could also be 'genericized' like so:
template <typename T>
T clip(const T& n, const T& lower, const T& upper) {
return std::max(lower, std::min(n, upper));
}
更新
比利·奥尼尔补充说:
请注意,在 Windows 上,您可能必须定义 NOMINMAX,因为它们定义了冲突的最小和最大宏
Note that on windows you might have to define NOMINMAX because they define min and max macros which conflict
这篇关于剪辑数字的最有效/优雅的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:剪辑数字的最有效/优雅的方法?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07