+4  A: 

Is "total_pairs" an int? If so, the divide is done as integer division. You need to explicitly cast one of the numbers to a double (and the other will be automatically promoted to double):

double percent = ((double)total_pairs)/10000; // or just simply 10000.0
Jim Buck
It obviously doesn't matter for this small example, but I would suggest using the more verbose static_cast<double> as it can be difficult to find c-style casts.
CTT
You can also write: double percent = double(total_pairs)/double(10000). Fewer parens.
Mr.Ree
+2  A: 

Dividing integers gives you an integer in C and C++ (I am not sure about the right English word for the corresponding operation, but 10/4 gives you 2, etc... that is the integer part of the division). So the following:

double a = 1000 / 10000;

First compute, as an int, 1000 / 10000 (0 in this case), and then cast this to double.

Casting the argument is one way - I prefer to simply input float instead of integers myself, but that's personal preference:

double a = 1000. / 10000.;

(just one is enough: that is 1000 / 10000. will work as well).

David Cournapeau
Notationally, I'd prefer to see a zero after the decimal point; it makes it clearer that the dot is not just a grubby mark on the screen.
Jonathan Leffler
+3  A: 

Yes, this is the case, the following performs integer division. The result (0) is then converted to a double.

double percent = 5600/10000

The line below forces 5600 to be a double so now you have actual division of doubles

double percent = (double) 5600/10000

If one of your numbers is a constant you can just make sure you use decimal format for it to force floating point division:

double percent = 5600.0/10000

Another trick I sometimes use is to multiply by a 1.0 which converts what follows to a double:

double percent = 1.0 * inta / intb
+2  A: 

The problem with your code:

double percent = (double) 5600/10000;

is you are assuming that the typecast applies to the 5600. It does not. What actually happens is the division is done (and truncated, because both numbers are ints), and then the final result is cast to a double. So, you get the truncated result. The above code is equivalent to:

double percent = (double) (5600/10000);

What you need for the division to function as you need is for the numerator (first number) to be a double. You can do this by wrapping the cast in parentheses

double percent = ((double) 5600)/10000;

Which is more useful if the numerator is actually a variable. Alternately you can just put a decimal place at the end of the number, if you are dealing with a numerical constant.

double percent = 5600.0/10000;
MichaelM
You have it backwards. “(double) 5600/10000” groups as “((double) 5600)/10000”.
Derek Ledbetter
Ah man you're absolutely right!That's what I get for going on a rant without compiling a test program to make sure I'm correct.
MichaelM