Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in c not giving expected value

Tags:

c

double

division

When doing a division im getting a rounded answer?

double div;
div = 25/8;
printf("%lf",div);

When i do this prints out 3.0000

why dont i get 3.125?

like image 924
theForgottenCoder Avatar asked Oct 20 '25 21:10

theForgottenCoder


2 Answers

Because you are doing an integer division, try with:

div = 25.0/8;

or

div = (double)25/8;

Typing 25.0 means a double literal. You could also use 25.f for a float literal. Both of these trigger floating point division.

like image 110
Eric Fortin Avatar answered Oct 23 '25 11:10

Eric Fortin


Typecast it, i.e. change it to:

double div;
div = (double)25/(double)8;
printf("%lf",div);
like image 22
brokenfoot Avatar answered Oct 23 '25 11:10

brokenfoot