[英]How can i make two values constrain each other consistently?
I have two variables, static int16_t min
and static int16_t max
.我有两个变量,
static int16_t min
和static int16_t max
。
I want them to constrain each other, so that我想让他们互相约束,这样
min
is never greater than max
, and min
永远不会大于max
,并且max
is never less than min
. max
永远不会小于min
。 Also, each value needs to be restricted within the value range of 0 - 15 (The variables are declared as int16_t since they're used for several purposes, besides the range in this particular instance).此外,每个值都需要限制在 0 - 15 的值范围内(变量被声明为 int16_t,因为除了这个特定实例的范围之外,它们还有多种用途)。
I tried the following code:我尝试了以下代码:
min = constrain(min, 0, max);
max = constrain(max, min, 15);
This works as intended for min
's value, meaning: once min
is increased up to max
it won't increase beyond the value of max
.这适用于
min
的值,意思是:一旦min
增加到max
它就不会增加超过max
的值。 On the other hand, when the value of max
is decreased to a value equal to min
, it keeps reducing both values until they're both down to 0.另一方面,当
max
的值减小到等于min
的值时,它会不断减小两个值,直到它们都减小到 0。
I have a hard time figuring out how the logic can be solved, and would appreciate any advice that makes the logic consistent for both values , so in other words I'd be fine with a solution that either makes:我很难弄清楚如何解决逻辑,并且希望能够使逻辑对两个 values 保持一致的任何建议,因此换句话说,我可以使用以下解决方案:
Short answer: Encapsulation.简短的回答:封装。
What you describe is an invariant.你所描述的是一个不变量。 Invariants are guaranteed by user defined data types by encapsulating the private data and only provide the user access to methods that have the invariant as post condition.
不变量由用户定义的数据类型通过封装私有数据来保证,并且只为用户提供对将不变量作为后置条件的方法的访问。
Only to outline the idea:仅概述想法:
class min_max {
int min;
int max;
void normalize_min() { if (min > max) min = max; }
void normalize_max() { if (max < min) max = min; }
public:
min_max(int a,int b) : min(std::min(a,b)), max(std::max(a,b)) {}
void set_min(int x) {
min = x;
normalize_max();
}
void set_max(int x) {
max = x;
normalize_min();
}
int get_max() { return max; }
int get_min() { return min; }
};
From outside the class there is no way to reach a situation where max < min
.从课堂外,无法达到
max < min
。
Consider the comment by Yakk on your question.考虑 Yakk 对您的问题的评论。 I wasn't sure what you actually want and for the above I assumed after calling
mm.set_max(a)
we can assert that mm.get_max() == a
and only min
is adjusted (vice versa for set_min
).我不确定你真正想要什么,对于上面我假设在调用
mm.set_max(a)
我们可以断言mm.get_max() == a
并且只有min
被调整(反之亦然set_min
)。 Other solutions are possible, for example you could throw an exception when the user attempts to set a max
that is larger than min
, or signal an error in a different way.其他解决方案也是可能的,例如,当用户尝试设置大于
min
的max
或以不同方式发出错误信号时,您可以抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.