問題描述
給定一個實數 (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
這篇關于剪輯數字的最有效/優雅的方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!