简体   繁体   中英

Why am I getting not declared in this scope error

This is what I have to do for my assignment. Firstly, you will need to write a function: int average(int *array, int nLen); which returns the average value of an array of integer values. (To prevent overflow, it is suggested to use a long internal variable). The Spirit Level function will run a loop. For each iteration the Z-component of gravitational acceleration will be sampled four times at 50ms intervals and stored in a suitably sized array.

int average (int * array, int nlen);  // assuming array is int
{
  long sum = 0L;  // sum will be larger than an item, long for safety.
  for (int i = 0; i < nlen; i++)
  {
    sum += array [i] ;
  return  ((int) sum) / nlen ;

nlen not declared in scope is the error message

there appear to be a few issues with this function. First and foremost, there are no closing curly braces for the for loop or the function. Additionally, you do not want a semicolon after the name and parameters of the function if you are following it with the definition. Try defining your function as:

int average(int *array, int nlen) {
    long sum = 0L;
    for (int i=0; i<nlen; i++) {
        sum += array[i];
    }
    return ((int) sum) / nlen;
}

However, I would also caution you that defining sum as a long but then casting it back to an int before performing the division could lead to incorrect answers, and will likely not be doing exactly what you intend. For example, if sum would indeed overflow an int type, it will be incorrect when you cast it back to an int . If you want your result to be accurate, it would be best to perform the division as a long and then cast the result to an int to return it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM