Division in c not giving expected value

16,584

Solution 1

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.

Solution 2

Since both the numerator and denominator are integer values, division operator performs only integer division and skips fractional part for optimization purpose.

So you need to specify by typecasting or making 25 as 25.0 or 8 as 8.0 that you want fractional part as well.

Solution 3

Typecast it, i.e. change it to:

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

Solution 4

Either typecast explicitly to double data type or change numerator to get desired value i.e. 25.o or use floating point literal 25.f.

Share:
16,584
theForgottenCoder
Author by

theForgottenCoder

Updated on August 03, 2022

Comments

  • theForgottenCoder
    theForgottenCoder almost 2 years

    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?

  • theForgottenCoder
    theForgottenCoder about 10 years
    what about in the situation i have an array and i want to divide it by the size of the arrays for example like --------- div = (sizeof(fulltext) / sizeof(fulltext[0])) / 8;
  • Eric Fortin
    Eric Fortin about 10 years
    sizeof returns an unsigned int so you'll get integer division. If you really want a double out of it, you can cast the return.
  • M.M
    M.M about 10 years
    An array is always a whole multiple of its element size
  • Eric Fortin
    Eric Fortin about 10 years
    Well there's a '/8' at the end so it might get to a floating point value.