Patryk
Patryk

Reputation: 279

Calculating mean of an array

Hello I'm having issues calculating the mean of in my function, the program compiles however I don't get the intended answer of 64.2 to print out and instead get a random set of integers and characters.

This is not the entirety of the code but only the appropriate variables and functions.

        // main function and prototyping would be here
 int size=0;
 float values[]={10.1, 9.2, 7.9, 9.2, 13.0, 12.7, 11.3};


    float mean(float values[], int size)
   {
      float sum = 0;
      float mean = 0;

            for (size = 0; size > 7; size++)
                  {
                    sum += values[size];
                    mean = sum / 7;
                  }

return mean;
    }

Upvotes: 0

Views: 384

Answers (3)

sabbahillel
sabbahillel

Reputation: 4425

 for (size = 0; size > 7; size++)

Since size is initialized as 0, and it is incremented by 1, it becomes 1 at the end of the first iteration and fails the test (it is not > 7). Thus, it immediately exits the loop.

Secondly, you calculate mean inside the loop when you should calculate it after the loop is complete. Theoretically, you should get a correct value since you redo it as the mean of the sums to that point in the loop, but it is a waste of time. You also wipe out size by redefining it.

float mean(float values[], int size)
{
  float sum = 0;
  float mymean = 0;

  for (int i = 0; i < size; i++)
    {
       sum += values[i];
    }
  mymean = sum / size;

  return mymean;
}

Upvotes: 1

tadman
tadman

Reputation: 211740

Why is the test size > 7 there? Expecting your initial value to have an unusually large value of zero? It's likely that you mean size < 7, though using arbitrary magic numbers like that is trouble.

What you probably want is:

float mean(float* values, int size)
{
  float sum = 0;
  for (int i = 0; i < size; ++i)
     sum += values[i];

  return sum / size;
}

To be more C++ you'd want that signature to be:

float mean(const float* values, const size_t size)

That way you'd catch any mistakes with modifying those values.

Upvotes: 0

brokenfoot
brokenfoot

Reputation: 11649

Change your loop like so:

for (size = 0; size < 7; size++)
{
    sum += values[size];
}
mean = sum / 7;
  1. Your terminating condition for for loop isn't right.
  2. Move the mean out of for loop.

Upvotes: 1

Related Questions