Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I divide two integers inside a double variable? [closed]

Tags:

c++

I am working on a lab for school that runs 10 trails of 10000 5 card hands. I have to find flushes and pairs in each hands. I have to find the percentage of pairs and flushs per trail.

My problem is when I try to get the percentage of a pair of one trail for example

double percent =  total_pairs/10000;

or

double percent = 5600/10000;

my output becomes 0 when I want to print out 2 decimal places I get the following

0.00

using this code

cout<<setiosflags(ios::fixed | ios::showpoint);
cout<<setprecision(2)<<percent<<endl;

but I still get zero I get actual numbers when I cast it like so

double percent = (double) 5600/10000;

is this correct because I don't want it to truncate my outputs or am I missing something

Hope you can understand me.

like image 424
Ender Avatar asked Dec 06 '25 06:12

Ender


2 Answers

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
like image 124
naumcho Avatar answered Dec 07 '25 20:12

naumcho


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
like image 44
Jim Buck Avatar answered Dec 07 '25 20:12

Jim Buck