2

我试图确保int x大于或等于 0 但小于 1080(在这种情况下为屏幕尺寸)。

我想出了这个

int x = 123;
x = std::min(std::max(x, 0), 1080);

这看起来很丑陋。有没有更好的方法来实现这一目标?

4

4 回答 4

8

如果你生活在未来,你可以std::clamp从 C++17 开始使用:

x = std::clamp(x, 0, 1080);
于 2017-01-08T17:32:13.613 回答
2

天真的解决方案看起来也不错:

int x = 123;
if (x < 0)
    x = 0;
if (x > 1080)
    x = 1080;

或将所有内容包装在一个函数中:

template<typename T>
T between(const T x, const T min, const T max){
   if (x < min)
       return min;

   if (x > max)
       return max;

   return x;
}

int x = between(123, 0, 1080);
于 2017-01-08T17:34:31.173 回答
1

使用无符号作为 x 的类型。这会自动将其限制为非负数。

然后你只剩下对 std::min 的调用,这至少对我来说是可口的。

构建一个在构造上采用 int 并且具有到 int 的转换运算符的类也是合理的,但需要相当多的样板文件。

于 2017-01-08T17:30:42.893 回答
-1

为什么不做这样的事情呢?

int x = 123; /* Or some arbitrary number */
bool bIsInRange = (x >= 0) && (x < 1080);
if(!bIsInRange){
   std::cout << "Variable 'x' is not between 0 and 1080." << std::endl;
   return 1;
} // else, x is fine. Continue operations as normal.
于 2017-01-08T17:32:54.060 回答