I'm trying to write a problem that calculates and prints the mean and variance of two numbers. I must create a function to calculate it and then print the results only in the main function. The way I chose was using one array of 2 positions that has the mean value in the first position and the variance value in the second position. I believe the issue is assign the values to the array, thate's waht I'm not being able to do correctly. Could someone please explain me that with some coding? If there's another way of doing that which is not using the array, it's also valid.
int * statistics (float x, float y){
double mean, var;
int i;
static int Arr[2];
mean = (x y)/2;
var = ((x-mean)*(x-mean) (y-mean)*(y-mean)) /2;
for (i = 0; i < 2; i) {
if (i=0)
{
Arr[i] = mean;
}
else
{
Arr[i] = var;
}
return Arr;
}
int main(){
int num1, num2, result;
num1 = 10;
num2 = 5;
result = statistics(num1, num2);
printf("%lf -- %lf", result[0], result[1]);
return 0;
}
CodePudding user response:
if (i=0)
is not the same as if (i == 0)
.
The first is an assignment of 0, which always returns false
(if you were to assign anything other than 0 it would always return true
). The second is a check if i
is actually 0.
This should in theory result in an endless loop, since i
is always set back to 0 and you keep writing var
to Arr[0]
.
CodePudding user response:
Here are a list of everything that is wrong with the program:
- There should be a closing brace after this to close the for loop:
else
{
Arr[i] = var;
}
- As @Klickmann said
if (i=0)
is not the same asif (i == 0)
. - Lots of incorrect types here and there.
This works:
#include <stdio.h>
#include <stdlib.h>
double *statistics(float x, float y)
{
double mean, var;
/* malloc */
double *Arr = malloc(2 * sizeof(double));
mean = (x y) / 2;
var = ((x - mean) * (x - mean) (y - mean) * (y - mean)) / 2;
/* No need for loop */
Arr[0] = mean;
Arr[1] = var;
return Arr;
}
int main()
{
float num1, num2;
double *result;
num1 = 10.0F;
num2 = 5.0F;
result = statistics(num1, num2);
printf("%lf -- %lf", result[0], result[1]);
/* Done with result. Free it. */
free(result);
return 0;
}
You should use dynamic memory allocation (malloc()
and free()
) if you want to return an array.