Function returns "0" from a simple division calculation

Jul 2, 2011 at 7:42pm
I know this is a simple problem, but I have a function that will not return a double or float value from a simple calculation...for example:

double r = (3 / 50);

return r;

For whatever reason, this function returns 0 instead of 0.06. Similar functions in my program return correct values...any ideas why all of a sudden this function will not return double or float values?
Last edited on Jul 2, 2011 at 7:50pm
Jul 2, 2011 at 7:51pm
integer division returns an integer. The result is rounded down. Divide doubles : 3.0/50
Jul 2, 2011 at 8:15pm
If the value r was calculated by the function (min(r, x)), does the function min() return a double or an integer? Ultimately the code reads:

double minimum = min(r, x);
cout << Division(minimum);

double Division (double minimum) {return ( minimum / 50)};

From the Division function, the returned value is equal to zero...
Last edited on Jul 2, 2011 at 8:16pm
Jul 2, 2011 at 8:19pm
The function returns whatever you told it to return. If min returns a double, then it returns a double.

The problem is not the function, it's your division:

 
double r = (3 / 50);


It doesn't matter that r is a double here. 3 and 50 are both integers. Therefore the result of this division is also an integer (so you get 0).


Do what hamsterman said and change one or both of them to doubles:

double r = (3.0 / 50.0);
Jul 2, 2011 at 8:30pm
I see...thanks that worked...
Topic archived. No new replies allowed.