简体   繁体   English

在 C++ 中定义变量的最大值和最小值

[英]Defining max and min values for a variable in C++

I'm working on a project, and was curious about if there's an easy way to define custom max and min values for a double variable.我正在做一个项目,并且很好奇是否有一种简单的方法可以为双变量定义自定义最大值和最小值。 At the moment, there's a quite large if-else if block handling this, but my question is can I do something in the variable's declaration so that these checks are unneeded?目前,有一个相当大的 if-else if 块来处理这个问题,但我的问题是我可以在变量的声明中做些什么,这样就不需要这些检查了吗?

was curious about if there's an easy way to define custom max and min values for a double variable.很好奇是否有一种简单的方法可以为双变量定义自定义最大值和最小值。

Since C++17, there is standard library function std::clamp that you can use to set out of-bound value to maximum / minimum depending on which boundary it exceeded.自 C++17 以来,有标准库 function std::clamp可用于根据超出的边界将超出范围的值设置为最大值/最小值。

If you need some other behaviour for out-of-bound values, or need to support older C++, the you can use if-else to check whether a new value is within the allowed bounds.如果您需要对超出范围的值进行一些其他行为,或者需要支持较旧的 C++,您可以使用 if-else 检查新值是否在允许的范围内。

At the moment, there's a quite large if-else if block handling this,目前,有一个相当大的 if-else if 块处理这个,

Two conditionals should be sufficient.两个条件就足够了。 One for upper bound, another for lower.一个用于上限,另一个用于下限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM