This is what I have currently, and I have no idea what to do to make it run:
void avg_sum(double a[], int n, double *avg, double *sum) {
int i;
*sum = 0.0;
for (i = 0; i < n; i )
*sum = a[i];
*avg = *sum / n;
}
int main () {
int array[5] = {1, 2, 3, 4, 5};
int avg = 3;
int sum = 2;
avg_sum(array, 5, avg, sum);
}
I tried manipulating the arguments for running the function, but I can't figure out how to make it work. It can be simple, I just have to write a program to test the avg_sum
function. That portion must remain the same.
CodePudding user response:
You want this:
int main () {
double array[5] = {1, 2, 3, 4, 5}; // use double
double avg = 3;
double sum = 2;
avg_sum(array, 5, &avg, &sum); // call with &
}
avg_sum
operates ondouble
s, therefore you need to provide doubles.- parametrers 3 and 4 must be pointers to double, therefore you need to use the address operator
&
.
All this is covered in the first chapters of your beginner's C txt book.
CodePudding user response:
For starters these initializations
int avg = 3;
int sum = 2;
does not make a sense.
At least it will be more meaningfully to initialize these variables by zero
int avg = 0;
int sum = 0;
The function avg_sum
expects that the third and fourth arguments will be accepted by reference through pointers to them.
void avg_sum(double a[], int n, double *avg, double *sum) {
So the function must be called like
avg_sum(array, 5, &avg, &sum);
Also the function expects that the first, third and fourth arguments declared with the type specifier double
but you are passing arguments declared with the type specifier int
.
The function itself should be declared and defined the following way
void avg_sum( const int a[], size_t n, double *avg, int *sum )
{
*sum = 0;
for ( size_t i = 0; i < n; i )
{
*sum = a[i];
}
*avg = n == 0 ? 0.0 : *sum / n;
}
So within main the variables avg
and sum
have to be declared like
double avg = 0.0;
int sum = 0;
Also after the call of the function
avg_sum(array, 5, &avg, &sum);
it seems you should output the obtained values like for example
printf( "sum = %d, average = %.2f\n", sum, avg );