7331| 2
|
[求助] Arduino从入门基础到实践书中 第十二个项目 蜂鸣器旋律发声 |
本帖最后由 dafenqi5219 于 2017-5-16 21:12 编辑 在《Arduino入基础到实践》书中第十二个项目中我有一点不明白就是为什么取得长度要为数组个数的一半 length = sizeof(tune)/ sizeof(tune [0]); 然后书中给出的解释是: 在播放的时,数组有26个元素只调取了一半13个元素,不太明为什么要这样处理 for (int x = 0; x < length; x++) { tone (8, tune[x]); delay(1500 * duration[x]); noTone(8); } delay(5000); [mw_shl_code=c,true]#include "Arduino.h" //项目12蜂鸣器发声旋律演奏 #define NOTE_C3 131 #define NOTE_CS3 139 #define NOTE_D3 147 #define NOTE_DS3 156 #define NOTE_E3 165 #define NOTE_F3 175 #define NOTE_FS3 185 #define NOTE_G3 196 #define NOTE_GS3 208 #define NOTE_A3 220 #define NOTE_AS3 233 #define NOTE_B3 247 #define NOTE_C4 262 #define NOTE_CS4 277 #define NOTE_D4 294 #define NOTE_DS4 311 #define NOTE_E4 330 #define NOTE_F4 349 #define NOTE_FS4 370 #define NOTE_G4 392 #define NOTE_GS4 415 #define NOTE_A4 440 #define NOTE_AS4 466 #define NOTE_B4 494 #define WHOLE 1 #define HALF 0.5 #define QUARTER 0.25 #define EIGHTH 0.125 #define SIXTEENTH 0.0625 int tune[] = { NOTE_C4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_B3, NOTE_G3, NOTE_A3, NOTE_C4, NOTE_C4, NOTE_G3, NOTE_G3, NOTE_G3, NOTE_F3, NOTE_F3, NOTE_G3, NOTE_F3, NOTE_E3, NOTE_G3, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_A3, NOTE_B3, NOTE_B3, NOTE_C4, NOTE_D4 }; float duration[] = { EIGHTH, QUARTER+EIGHTH, SIXTEENTH, QUARTER, QUARTER, HALF, HALF, HALF, QUARTER, QUARTER, HALF+QUARTER, QUARTER, QUARTER, QUARTER, QUARTER, QUARTER, QUARTER, HALF+QUARTER }; int length; //The setup function is called once at startup of the sketch void setup() { // Add your initialization code here pinMode(8, OUTPUT); length = sizeof(tune) / sizeof(tune[0]); // length = sizeof(tune); } // The loop function is called in an endless loop void loop() { //Add your repeated code here for (int x = 0; x < length; x++) { tone (8, tune[x]); delay(1500 * duration[x]); noTone(8); } delay(5000); } [/mw_shl_code] |
问题找到了sizeof(tune)也是测量的数组大小,而不是数组元素个数, 一般int类型的变量根据编译器的不通会出现不同的大小,我是用的是的c-free5.0 显示是占用四个字节 所以求出的length是得出数组的元素个数 length = sizeof(tune) / sizeof(tune[0]); 应该为 54/2 或者 108/4 (不同的编译环境int类型变量会有所不同) 但是肯定不是26/2 这本书写错了大家有没有发现。 |
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed