25

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

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
Chad Carisch
  • 2,422
  • 3
  • 22
  • 30
  • 2
    "decimal" is a representation (as "hexadecimal", "octal", "binary") which applies to integer or non-integer numbers. You mean, I guess, "get a non-integer result". – leonbloy Jun 04 '10 at 19:49
  • This is how you get fractions (rational numbers) with integer division `printf("%d %d/%d" x/y, x%y, y);`. Are you sure you don't want a non-integer result? – Brendan Sep 22 '14 at 05:52

2 Answers2

47

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.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • Right. Convert the integers before you perform the division. – DOK Jun 04 '10 at 16:33
  • double tp; double x; x = tn; //(tn is a int) normally 10 tp = x/fn; // fn is also a int (normally 5) but i still get 0 – Chad Carisch Jun 04 '10 at 16:50
  • @Chad: The code looks right. How have you determined that the result is zero? Are you doing something like `printf("%d", tp)`? That tries to print the content of a double as an int, and you won't get the correct results. Your compiler should have warned you if you did that. For a double the format string is `%lf`. – Mark Rushakoff Jun 04 '10 at 16:56
  • its actually being sent to a gui... tailsPer = tailsNum / ((double)curNum); //tailsper is a double [tailsPerField setIntValue:tailsPer]; // this is in cocoa – Chad Carisch Jun 04 '10 at 17:29
4

Use type-casting. For example,

main()
    {
        float a;
        int b = 2, c = 3;
        a = (float) b / (float) c;     // This is type-casting
        printf("%f", a);
    }
Pranav Totla
  • 2,182
  • 2
  • 20
  • 28