Mohamed MosȜd Mohamed MosȜd - 23 days ago 14
C Question

how a function in C can return multiple values?

In the following code, the function

avg(int i,int j,int k,int *pint,double *pfloat)
computes the average of
i
,
j
,
k
and returns the integer and float part of the result individually. As an example, if
average = 22.45
it should return 22 and 0.45.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

void avg(int i,int j,int k,int *pint,double *pfloat)
{
double average=(i+j+k)/3;
*pfloat=average-(floor(average));
*pint=floor(average);
}

int main()
{
int Integer=0;
double rem=0;
avg(2,4,5,&Integer,&rem);
printf("%d\n%lf",Integer,rem);
return 0;
}


the output is 3 and 0 why ??

Answer
double average=(i+j+k)/3;

This is an integer division. To get a useful floating point division, you can add a "." to the constant like so:

double average=(i+j+k)/3.;

making it a floating point constant (which in turn makes the division be done as floating point division).

Comments