首页 > 解决方案 > Arduino 从给定数组中选择一个随机词

问题描述

我有这段代码可以在 LCD 上打印一个单词:

void setup(){
lcd.print("Hello World");
}

我希望它从这个数组中选择一个随机词:

const char *words[] = {"Happy","Sad","Angry","Worried","Shy","Excited","Suprised","Silly","Jealous","Hurt","Cold","Hot","Energized","Bored","Sick","Love","Upset"};

所以基本上使用这个数组,我希望它从这个数组中选择一个随机单词,然后使用 lcd.print 方法将它显示在 LCD 上。有任何想法吗?对不起,如果答案很明显,我只是 Arduino 的初学者。

标签: c++arraysrandomarduino

解决方案


首先找到数组的长度,然后用它random来获得一个达到该界限的数字:

const int len = sizeof(words) / sizeof(words[0]);
lcd.print(words[random(len)]);

推荐阅读