Search code examples
cfunctionvariablesinteger-division

Wrong answer of average function?


I'm practically new to C programming and I've been trying to get a simple average function right, but the fractional part of the answer keeps messing up...??

#include <stdio.h>
#include <float.h>

float cal(int num1,int num2,int num3);

int main(){
    int a,b,c;
    float avg;

    a=10;
    b=5;
    c=11;

    avg=cal(a,b,c);
    printf("Average is : %E\n", avg);
    return 0;
}

float cal(int num1,int num2,int num3){
    float avg1;
    avg1=(num1+num2+num3)/3;
    return avg1;
}

The answer (avg) should be 8.66666666667, but instead I get 8.00000000...


Solution

  • You're doing integer division here. Cast it to float (at least one of them) or use float literals before division to force it to use float division.

    For example, change

    avg1=(num1+num2+num3)/3;
    

    to

    avg1=(num1+num2+num3)/(float)3;  // 1. cast one to float
    avg1=(num1+num2+num3)/3.0f;      // 2. use float literals