首页 文章

Arduino 'for'错误

提问于
浏览
1

我已经为我的Arduino制作了一个程序,它将按升序或降序排序五十个随机数的数组,我想我已经把它弄好了,但是当我运行它时,我收到一条错误消息“期望不合格的id之前”为'“ .

int array [50];
int i = 0;

void setup() {
   Serial.begin(9600); // Load Serial Port
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println ("Position " + array[i]);
  delay (2000);

}

for (i <= 50) {      <-----*Here is where the error highlights*--->
  int n = random (251); // Random number from 0 to 250
  array[i] = n;
  i++;
}

// Bubble sort function
void sort (int a[], int size) {
    for(int i=0; i<(size-1); i++) {
        for(int o=0; o<(size-(i+1)); o++) {
                if(a[o] > a[o+1]) {
                    int t = a[o];
                    a[o] = a[o+1];
                    a[o+1] = t;
                }
        }
    }
}

我已注释显示错误的位置 . 我需要通过这个来测试我的代码,我不知道如何解决它!

2 回答

  • 0

    你写错了 . 有for循环的伪代码:

    for(datatype variableName = initialValue; condition; operation){
     //your in loop code
    }
    //Code wich will be executed after end of for loop above
    

    在您的情况下,它将如下所示:

    for(int i = 0; i < 50 ; i++){
        int n = random (251); // Random number from 0 to 250
        array[i] = n;
    }
    
    • 另一件事是,您正在尝试迭代数组 . 第一个索引是0.它表示 last index is 49 not 50 . 如果您尝试访问第50个索引,它将导致您的程序崩溃 .

    • 最后一点是,我们所讨论的for循环不是任何方法 . 它永远不会被执行 .

  • 0

    for循环需要三个部分参数:

    • 用于计算迭代次数的变量

    • 必须为真的条件才能继续

    • 增量系数

    每个部分应以分号分隔

    所以你的for循环应该像这样开始:

    for(int i = 0;i <= 50; i++){ 
        //code here 
    }
    

    Official arduino For Loop Reference

相关问题