-1

Why the output of x in the programming is 0 instead of 1/2?

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

int main()
{   
        double *xp,x;
        xp = &x;
        *xp = 1/2;
        printf("%f\n",x);
        return 0;
}

give the result of

0.000000
Tam Lam
  • 135
  • 1
  • 3
  • 13

2 Answers2

2

Because 1/2 is 0. On the other hand, 1.0/2.0 is 0.5. The rule is, if both operands are integral, the division is integral as well. It then gets assigned to a float storage, and then gets printed as a float; but by that time, it's too late.

Nothing to do with pointers, really.

Amadan
  • 191,408
  • 23
  • 240
  • 301
1

Because you are dividing two integers.

1/2;

The result of 1 / 2 is an integer result, zero. To correct this:

1.0 / 2.0;

This will return a floating point result.

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67