最有效的/优雅的方式来夹了多少? [英] Most efficient/elegant way to clip a number?

查看:119
本文介绍了最有效的/优雅的方式来夹了多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于一个真正的(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));
}

这EX pression也可能是泛型化,像这样:

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

这篇关于最有效的/优雅的方式来夹了多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆