Division result is always zero

29,659

because in this expression

t = (1/100) * d;

1 and 100 are integer values, integer division truncates, so this It's the same as this

t = (0) * d;

you need make that a float constant like this

t = (1.0/100.0) * d;

you may also want to do the same with this

k = n / 3.0;
Share:
29,659
VaioIsBorn
Author by

VaioIsBorn

Updated on July 09, 2022

Comments

  • VaioIsBorn
    VaioIsBorn almost 2 years

    I got this C code.

    #include <stdio.h>
    
    int main(void)
    {
            int n, d, i;
            double t=0, k;
            scanf("%d %d", &n, &d);
            t = (1/100) * d;
            k = n / 3;
            printf("%.2lf\t%.2lf\n", t, k);
            return 0;
    }
    

    I want to know why my variable 't' is always zero (in the printf function) ?

  • Rich
    Rich about 14 years
    Or just use d / 100.0.
  • Christopher
    Christopher over 5 years
    In my situation this is what I ended up doing to stop getting 0 for my division: Double ratio = (Convert.ToDouble(x) / Convert.ToDouble(y));
  • TamaMcGlinn
    TamaMcGlinn almost 4 years
    @ChristopherD.Emerson That is C#; this question is about C (and also applies to C++).