Print average of integers in decimal form

Viewed 32

I have written a program where user can enter integers and in the ''menu'' choose option 'c' to calculate the average of all integers entered. My problem is that the program displays numbers as a whole instead of deciaml, like 3 instead of 3.7.

I have tried changing variables to double, float but it does not work. I'm gonna post my main and my avg function. In the main I cannot change variable types since other functions that use this variables will be affected. (Please ignore the placing of curly brackets.)

int main (){

    int measurements[10];
    int nrOfMeasurements = 0;
    char ch;

    while(1){
        printf("\nView(v)Enter(e)Compute(c):");
        scanf(" %c", &ch);
        switch(ch){
              case 'c':printf("Avg:%d\n", avg(measurements,nrOfMeasurements));
                       break; 
              }
      }
}

int avg(int a[], int n){

    int i;
    double sum=0,avg;
    for(i=0;i<n;i++){
        sum += a[i];
    }
    avg=sum/n;
    return avg;
}
1 Answers

Change

 int avg(int a[], int n){

to

 double avg(int a[], int n){

and use it like

printf("Avg:%f\n", avg(measurements,nrOfMeasurements));

If you need floating point output, you need to use the proper type and conversion specifiers.

Related