Code to ouput mean, max and min values of an array is returning wrong values

This code is supposed to print out mean, max and min value of an array in a structure but it is returning wrong values. Can someone please tell me what I am doing wrong. Please note that no changes is to be made on the main. Thanks


#include <iostream>
#include <cstdlib>

typedef struct {
int data[10];
float mean;
int min;
int max;
} A;
A compute(A a)
{
int i;
int j;
int data[10];
int min = data[0];
int max = data[0];
float mean = 0;
float sum = 0;

for (i=0; i<=10; i++)
{
sum += data[i];
mean = sum/10;
}
for (j=0; j<=10; j++)

if (data[j] < min)
{ min = data[j];
}

else if (data[j] > max)
{
max = data[j];
}
}

int main()
{
srand(NULL);
A a;
for (int i = 0; i < sizeof(a.data) / sizeof(a.data[0]); i++)
{
a.data[i] = rand();
std::cout << a.data[i] << std::endl;
}
a = compute(a);
std::cout << "mean: " << a.mean << std::endl;
std::cout << "min: " << a.min << std::endl;
std::cout << "max: " << a.max << std::endl;
return 0;
}

In the compute function, do not create whole new values of data, min, mean, max. You're meant to be working on the data already inside the struct. Use the data already inside the struct.
Last edited on
You have completely lost me.

I am a beginner in c++ and this is supposed to be c++ code.

Here is the question i am attempting to solve;


Supposed that the code is given as:


#include <iostream>
#include <cstdlib>
typedef struct {
int data[10];
float mean;
int min;
int max;
} A;
A compute(A a);
int main()
{
srand(NULL);
A a;
for (int i = 0; i < sizeof(a.data) / sizeof(a.data[0]); i++)
{
a.data[i] = rand();
std::cout << a.data[i] << std::endl;
}
a = compute(a);
std::cout << "mean: " << a.mean << std::endl;
std::cout << "min: " << a.min << std::endl;
std::cout << "max: " << a.max << std::endl;
return 0;
}
Write the function, compute(A a), to find the smallest/highest/mean value in the
array of the structure A, and return the structure.
See where you get the mean value from inside the struct, like this: a.mean ?

That's the mean value you're meant to be working on. So why, at the start of your compute function, are you doing this: float mean = 0; ? Why are you making a variable named mean? You're meant to be working on a.mean

Basically, your problem is that you don't understand what a struct is and how to use one. Stop trying to solve this problem. Go back to whatever you were meant to learn about struct from, and learn about struct.
Topic archived. No new replies allowed.