如何向数组中添加元素 - Arduino

3
我尝试用以下代码以空数组开始,然后生成一个随机数模式,但似乎无法使其正常工作。
 int sequence = {};

 random(1, 4);

 for (int i=0; i <= 7; i++){
 sequence[i] = random(1, 4);
 } 
3个回答

4

Arduino 基于 C++ 语言。

int sequence[8];

// You must initialize the pseudo-random number generator
// You can get a "random seed" using analogRead(0) if this
// pin isn't been used and unplugged.
randomSeed(analogRead(0));

for (int i=0; i <= 7; i++){
    sequence[i] = random(1, 4);

2
这是我会这样做的,它在我的Arduino IDE上编译得非常好。我认为没有必要种植rand函数,除非您的应用程序需要一个真正随机的数字(不可重复)。 https://www.arduino.cc/en/reference/random应该可以帮助您。
void loop() {
 int sequence[8]; // this is an array

 for (int i=0; i <= 7; i++){
 // use modulo to get remainder, add 1 to make it a range of 1-4
 sequence[i] = rand() % 4 + 1;
 }
}

1

那不是一个数组。
这个才是一个数组,int sequence[7];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接