2

c code :

 int main(void) {
 int i = 0, j = 0;
 double avg = 0;
 int *pi, *pj;
 double *pavg;

..

    pi = &i;
    pj = &j;
    pavg = &avg;

..

    *pi = 5;
    *pj = 10; 
    *pavg = (*pi + *pj) / 2;

here where it prints :

    printf("%lf\n\n", avg);

it prints 7.000000000

    return 0;
}
Eby
  • 93
  • 5

1 Answers1

7

When you do (*pi + *pj) / 2, you are doing integer arithmetic. The numbers after the decimal have already been discarded before you assign to the double variable.

One way is to do (*pi + *pj) / 2.0. One of the operands of the expression being a double, the other ints will be promoted to doubles before the expression is evaluated.

Another option is to typecast one of the variables to a double ((double)*pi + *pj) / 2. Here, the de-referencing operator being of higher precedence will be evaluated before the typecast.

babon
  • 3,615
  • 2
  • 20
  • 20