user3530421
user3530421

Reputation: 21

C++: getting errors with some code

i am kind of stuck with some code that im doing. what i have to do is in the comments.

//Write a function that computes the average value of an array of floating-point data:
//double average(double* a, int size)
//In the function, use a pointer variable, not an integer index, to traverse the array
//elements.



#include <iostream>

using namespace std;


double average(double* a, int size)

{
    double total = 0;
    double* p = a;
    // p starts at the beginning of the array
    for (int i = 0; i < size; i++)
    {
        total = total + *p;
        // Add the value to which p points
        p++;
        // Advance p to the next array element
    }
    return total / size;
}

to start with its not running. and 2ndly, am i actually going about doing the problem correctly? basically i tried following the book to go through all elements and then average it out after... but i have this strong feeling im missing something.

sorry if this seems to obvious for some of you guys. my still pretty new to all of this and my teacher doesn't exactly... well she doesn't teach us the coding aspect of C++. all she does is read from 5 out of 200+ slides and does hand tracing(not even pseudo code) and then throws us to the wolves by randomly picking us a coding assignment. the way she teaches is basically as if we already know how to code, which some of us do and some of us(like me) are seeing this for the very first time.

she hasnt even taught us how to use the compiler, so we are basically learning all of this ourselves. arg, sorry i went on a rant there. anyway can someone help with this?

Upvotes: 0

Views: 258

Answers (2)

Ashraful Haque
Ashraful Haque

Reputation: 559

This is another way,Here I used pointer notation to traverse the array.Depending on the value of i we can loop through the array.Another extra variable *p is not needed,because you already have *a for that.

double average(double* a, int size) {

  double total = 0;

  // *(a + i) starts at the beginning of the array
  for (int i = 0; i < size; i++)
  {
    total = total + *(a + i);
  }
  return total / size;
}

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385335

Your function is correct.

Here it is, running, and resulting in the correct output.

In case the problem is that you were not aware (though it seems unlikely), I had to add a main function and provide data for the function to work on:

int main()
{
    double array[5] = {1,2,3,4,5};
    std::cout << average(array, 5);
}

But that's all I had to do.

Upvotes: 3

Related Questions