-1

Possible Duplicate:
What is the behavior of integer division in C?

When I do a division calculation with an answer that's supposed to be between 1 and 0, it always returns 0.

Try this:

float a = 1;
float b = 2;
float c = a / b; //variable divide by variable gives 0.5 as it should
float d = 1 / 2; //number divide by number gives 0
float e = 4 / 2;
NSLog(@"%f %f %f %f %f", a,b,c, d, e);

I get this from the console:

2013-01-17 14:24:17.512 MyProject[1798:c07] 1.000000 2.000000 0.500000 0.000000 0.500000

I have no idea what is going on.

Community
  • 1
  • 1
Dylanthepiguy
  • 1,621
  • 18
  • 47
  • 3
    See [this](http://stackoverflow.com/q/3602827/1402846), [this](http://stackoverflow.com/q/2976011/1402846), [this](http://stackoverflow.com/q/2345902/1402846), [this](http://stackoverflow.com/q/4197841/1402846), [this](http://stackoverflow.com/q/8459351/1402846). – Pang Jan 17 '13 at 01:40
  • you can do 1.f/2, 1.0/2, 1/2.0000f, 1/(float)2... basically anything but 2 ints – Grady Player Jan 17 '13 at 01:43
  • 3
    Hey, wait a second... how come you got `0.500000` for `e` being `4 / 2`? It should have been `2.000000`. – Pang Jan 17 '13 at 01:57
  • @Pang: His pants are on fire. – President James K. Polk Jan 18 '13 at 12:05

1 Answers1

6

You're dividing integer with integer. The result will be an integer, the remainder is omitted:

1 / 2 = 0     The remainder (0.5) is omitted.

Only after the division is done, your result is passed into your float d variable.

EDIT: Right, I forgot to suggest a solution: Make sure at least one of your operands is a float.

1.0 / 2 = 0.5    

1 / 2.0 = 0.5
DrummerB
  • 39,814
  • 12
  • 105
  • 142