我为我的Arduino制作了一个程序,它将按升序或降序对五十个随机数的数组进行排序,我想我已经做对了,但是当我运行它时,我收到一条错误消息"在'for'之前预期非限定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;
}
}
}
}
我已经注释了显示错误的位置。我需要通过这个来测试我的代码,我不知道如何解决它!
你写错了。有 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。这意味着最后一个索引是 49 而不是 50。如果您尝试访问第 50 个索引,它将使您的程序崩溃。
最后一件事是,我们正在谈论的 for 循环没有任何方法。它永远不会被执行。
for 循环的参数需要三个部分:
- 用于计算迭代次数的变量
- 必须为真才能连续的条件
- 增量系数
每个部分应用分号分隔
所以你的 for 循环应该像这样开始:
for(int i = 0;i <= 50; i++){
//code here
}
官方 arduino 用于循环参考