Hello! I'm writing a program that calculates and shows the mean and variance of two integers. The result I'm getting is 7. But that's not the mean of 5 and 10 (num1 and num2). What can I do to show both mean and variance together on the screen? What should I put after return to show both mean and variance? Thank you. Code: #include <stdio.h> double statistics (int x, int y){ double mean, var; mean = (x+y)/2; var = ((x-mean)*(x-mean) + (y-mean)*(y-mean)) /2; return mean; } int main(){ int num1, num2; num1 = 10; num2 = 5; printf("%lf", statistics(num1, num2)); return 0; }
The reason to show 7 is because it is being treated as int. Pass the params as floats and then do the operation as float. To show the second output on the screen, you have to pass the param with reference or pointer and then get that as an output as well. Other option is to print the output in the function itself.
Thanks Shabbir, the problem of the mean value is solved. However, I must confess I'm not good at pointers so I'm writing a smaller program to show two values using a function with pointers. It's the same as of the video Code: #include <stdio.h> int pointers (int i){ int *p, *q; p=&i; q=p; } int main(){ printf("%d %d", pointers(10)); return 0; } It should show 10 10. I don't know what to put in the end of function pointers (return what??).
By pointer I mean you have to pass the address of the variable in the function and then assign the value withing the function. Something like: Code: int assign (int &i){ i = 10; } int main(){ int i; assign(i); printf("%d", i); return 0; }
But, returning to the original problema, is it possible to return the values of "mean" and "var" using an array?
I tried to do it with an array but I'm not getting it yet. Could you please explain me with some coding? Thanks a lot. Code: #include <stdio.h> 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 = mean; } else { Arr = var; } return Arr; } int main(){ int num1, num2; num1 = 10; num2 = 5; printf("%lf", statistics(num1, num2)); return 0; }
There are some basic issues in your code. 1. You need to learn to assign variables to the array first. It is Arr[0] and Arr[1] and not to the Arr like normal variables. 2. The return is an array and you can't just print them directly. Assign to an array and then print each element.
This is an exercise that I'm doing from an online course and it says not using printf in the statistics function, only in the main funtion. That's what complicates the exercise.
Yes this is fine but then you don't need to be doing Code: printf("%lf", statistics(num1, num2)); Instead you can do Code: result = statistics(num1, num2); printf("%lf -- %lf", result[0], result[1]);