How to get fractions in an integer division?

Chad Carisch picture Chad Carisch · Jun 4, 2010 · Viewed 86.9k times · Source

How do you divide two integers and get a double or float answer in C?

Answer

Mark Rushakoff picture Mark Rushakoff · Jun 4, 2010

You need to cast one or the other to a float or double.

int x = 1;
int y = 3;

// Before
x / y; // (0!)

// After
((double)x) / y; // (0.33333...)
x / ((double)y); // (0.33333...)

Of course, make sure that you are store the result of the division in a double or float! It doesn't do you any good if you store the result in another int.


Regarding @Chad's comment ("[tailsPerField setIntValue:tailsPer]"):

Don't pass a double or float to setIntValue when you have setDoubleValue, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.

For example, on my system, the file:

#include <stdio.h>
int main()
{
    double x = 3.14;
    printf("%d", x);
    return 0;
}

outputs:

1374389535

because the double was attempted to be read as an int.