首页 文章

Arduino - For Array with Array不工作

提问于
浏览
0

我在Arduino IDE中遇到for循环和数组的问题 .

  • test1执行 not 工作

  • test2确实有效

  • test3确实有效

我怎样才能让test2工作?

void test1(){
    for(int i=1; i<5; i++) {
    individualPixels[i]==1;
  }
}
void test2(){
    individualPixels[1]=1;
    individualPixels[2]=1;
    individualPixels[3]=1;
    individualPixels[4]=1;
  }
}
void test3(){
    for(int i=1; i<5; i++) {
    Serial.println(individualPixels[i]); //prints out 0 4 times
  }
}

提前致谢

4 回答

  • 1

    你're not actually assigning anything in test1, you'重新测试是否相等( individualPixels[i]==1 应该 individualPixels[i] = 1 ,注意单个等号) .

    此外,正如其他评论者所提到的,C / C使用零基索引 .

  • 0

    C / C使用零索引数组,因此test1和test3中的 for 循环应如下所示:

    for(int i=0; i<4; i++) {
        individualPixels[i]==1;
    }
    

    Test2有一个不匹配的括号,数组索引应该从零开始:

    void test2(){
        individualPixels[0]=1;
        individualPixels[1]=1;
        individualPixels[2]=1;
        individualPixels[3]=1;
      //} this shouldn't be here
    }
    
  • 0

    for循环以i = 1开始,应该为0,因为可以使用从0到size-1的索引访问数组中的元素 . 可以按如下方式访问包含4个元素的数组:

    array[0] --- first element
    array[1] --- second element
    array[2] --- third element
    array[3] --- fourth element
    

    除此之外,第一个for循环(不起作用)使用了==运算符,它检查两个变量是否相等,然后返回一个布尔值作为结果 . 相反,你应该使用单个=来设置值 .

    第二个测试有一个额外的},应删除

    我建议你开始实际学习编程,例如通过阅读(e)书,因为你会教自己坏习惯(以错误的方式访问数组),这可能有用,但可能效率不高 .

  • 1

    非常感谢你们所有人 . 我有一个包含60个索引的大型数组,并希望使用for循环设置其中一些1 . “==”是主要问题 . 它现在正如我想要的那样工作:

    void test1(){
        for(int i=1; i<5; i++) {
        individualPixels[i]=1;
      }
    }
    void test2(){
        individualPixels[1]=1;
        individualPixels[2]=1;
        individualPixels[3]=1;
        individualPixels[4]=1;
    }
    void test3(){
        for(int i=1; i<5; i++) {
        Serial.println(individualPixels[i]); //prints out 0 4 times
      }
    }
    

相关问题