目前,我有一个代码依赖于必须根据特定条件对 for 循环使用增量或减量的概念。示例是 Arduino 的两个轻触开关。一个会触发正增量,另一个触发负增量。
int inc; //Increment that is +1 or -1
int limit; //Minimum value for decrement and maximum value for increment
void loop() {
if(CONDITION) { //Condition for positive increment
i = 1;
limit = 15;
for(int i = 0; i <= limit; i = i + inc) {
//Statements
}
} else { //Condition for negative increment
i = -1;
limit = 0;
for(int i = 0; i >= limit; i = i + inc) {
//Statements
}
}
}
我想为您只更改参数(例如变量)的两种情况制作统一代码。现在我对更改增量没有任何问题。只需设置一个变为正或负 1 的变量。最小值和最大值也是如此。我的问题是比较运算符。
现在我自己做了一些搜索,但不太明白如何将我读到的内容应用于我在这里提到的这种情况。我将在这里引用链接。
我最大的问题是这些链接中的任何内容都没有在我记得的情况下在 for 等循环中应用了比较运算符。有没有办法为我所说的情况创建一个变量运算符?我的目标是能够删除我创建的 if else 条件中的 for 语句并将其移到外面。相反,我会将允许我设置比较运算符 <= 和 >= 的代码放入 if else 条件中。这是我希望它看起来像什么的想法。
int inc; //Increment that is +1 or -1
int limit; //Minimum value for decrement and maximum value for increment
void loop() {
if(CONDITION) { //Condition for positive increment
i = 1;
limit = 15;
/*
(Code to make the operator <=)
Wrong code technically but the concept would be
VariableOperator = <=
*/
} else { //Condition for negative increment
i = -1;
limit = 0;
/*
(Code to make the operator >=)
Wrong code technically but the concept would be
VariableOperator = >=
*/
}
for(int i = 0; /* i VariableOperator limit */; i = i + inc) {
//Statements
}
}
虽然这只是一个概念,因为我不知道它是如何工作的。代码可能会有所不同。我真的没有想法。