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;
}
Also, on your for loops: for (i=0; i<=10; i++) should be like for (i=0; i<10; i++). The reason is because the array element begins at 0 and your size of the array is 10. The total number of elements from 0 to 9 is 10.
Furthermore, on your A compute(A a) , what value are you planning to return to a = compute(a); (on main function)?
#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.
Firstly, don't post the same question in two places.
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.
Write the function, compute(A a), to find the smallest/highest/mean value in the
array of the structure A, and return the structure.
Your function returns object of type A. The A is a struct. It has member variables. While the function returns only one A object, the object contains many values, including the ones that you want.
Why do you use the typedef T U; syntax where the T is an unnamed struct type defined on the spot?
That syntax is used in C, but in C++ one can write: