0

目前,我有一个代码依赖于必须根据特定条件对 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
    }
}

虽然这只是一个概念,因为我不知道它是如何工作的。代码可能会有所不同。我真的没有想法。

4

1 回答 1

2

在 C++ 中有很多方法可以做到这一点,但复杂性各不相同。

但最简单和最清晰的(在我看来)是:

const int limit = 15;
for (int i = 0; i <= limit; ++i)
{
    int index = (inc > 0 ? i : limit - i);
    // Now use index instead of i
}

我在这里做了一些延伸,假设您要做的只是循环 16 次(从 0 到 15 或从 15 到 0 计数)。从您的代码中并没有完全清楚,因为它充满了错误,而且您从未真正用简单的术语描述过您想要什么。

请注意,您的非标准缩进样式使您的代码很难阅读。也许你喜欢 Python,但这不是我们在 C++ 中的做法。 编辑:问题已被编辑以修复缩进,但为了作者的利益,我将留下此评论。

于 2021-04-28T03:19:33.237 回答