0

Why does output equal zero in this code? Number 1 with weight of 2, number two with weight of 3 and number three with weight of 5. I can not understand why output = 0.

#include <stdio.h>

int main ()
{
    float A ,B, C ,MEDIA=0 ;
    scanf("%f%f%f",&A ,&B,&C);
    MEDIA+=1/2*A + 1/3*B + 1/5*C;
    printf("MEDIA = %.1f", MEDIA );

    return 0;
}
Tlacenka
  • 520
  • 9
  • 15
Asmaa
  • 11
  • 3

1 Answers1

3

MEDIA+=1/2*A + 1/3*B + 1/5*C;

Because 1/2, 1/3 and 1/5 will be evaluated as 0. Since they are integers. Either write

1.0/2, 1.0/3 and 1.0/5 instead. So the compiler will know to treat the result as float.

Or

MEDIA+=A/2 + B/3 + C/5;

P.S.

Maybe I am wrong but if I understood correctly what you wrote at the description then I think your calculation of the weighted average is incorrect. It should be something like

(A*2 + B*3 + C*5)/10

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45