-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
  • 2
  • 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
  • 179,482
  • 20
  • 216
  • 275
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,359
  • 4
  • 43
  • 65