计算Arduino中数组的总和

Calculate a sum of an array in Arduino

我正在尝试编写代码,将 5 个整数存储在数组中,然后计算 5 个存储值的总和。然后打印出5个值也是求和。

我试过这个:

const int sizeOFarray = 5;
int b[sizeOFarray] = {10, 20, 30, 40, 50};
int sum = 0;

void setup ()
{
  Serial.begin(9600);
}
void loop ()
{
  // sum of array b
  for ( int i = 0; i < sizeOFarray; i++ )
    sum += b[ i ];
  Serial.print('Sum of total elements of an array:') ;
  Serial.print(sum) ;
}

但它给了我一个奇怪的输出:

720031034735031034750031034765031034780031034795031034810031034825031034840031034855031034870031034885031034900031034915031034930031034945031034960031034975031034990031034100503103

它永远不会停止。

在您的代码中:

const int sizeOFarray = 5;
int b[sizeOFarray] = {10, 20, 30, 40, 50};


int sum = 0;   // you initialize sum once.

void setup ()
{
  Serial.begin(9600);
}
void loop ()
{
  // on the first pass sum == 0, no problem.
  // on the second pass, sum still holds the sum of values in the array.
  // to which you'll add again, creating the 'runaway' effect.   

  // sum of array b
  for ( int i = 0; i < sizeOFarray; i++ )
    sum += b[ i ];

  // After the first pass, sum hold the correct value, that is good.

  Serial.print('Sum of total elements of an array:') ;
  Serial.print(sum) ;
}

解决该问题的一个简单方法是将变量 sum 的声明和初始化移到 loop() 中,在打印输出中添加换行符也会有所帮助,如:

void loop ()
{
  int sum = 0; 
  // sum of array b
  for ( int i = 0; i < sizeOFarray; i++ )
    sum += b[ i ];

  Serial.print('Sum of total elements of an array:') ;
  Serial.println(sum) ;  // print sum and a newline. 
}

这应该产生这个输出:

Sum of total elements of an array:150
Sum of total elements of an array:150
Sum of total elements of an array:150
Sum of total elements of an array:150
Sum of total elements of an array:150
Sum of total elements of an array:150

注意:您可以通过取消变量 SizeOfArray 来节省一些 RAM space...

int b[] = {10, 20, 30, 40, 50};

void setup ()
{
    Serial.begin(9600);
}    

void loop()
{
    int sum = 0;
    for (int i = 0; i < sizeof(b) / sizeof(b[0]); ++i)
        sum += b[i];

    Serial.print("sum: "); 
    Serial.println(sum);
}