views:

204

answers:

1

how do you divide two integers and get a decimal answer? in xcode..

the only thing i could was find http://www.gnu.org/s/libc/manual/html_node/Integer-Division.html

this method will not allow me to have a decimal answer...

+10  A: 

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
Right. Convert the integers before you perform the division.
DOK
double tp;double x;x = tn; //(tn is a int) normally 10tp = x/fn; // fn is also a int (normally 5) but i still get 0
Chad
@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
its actually being sent to a gui... tailsPer = tailsNum / ((double)curNum); //tailsper is a double[tailsPerField setIntValue:tailsPer];// this is in cocoa
Chad