22

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) ?

Jayant Tripathi
  • 385
  • 3
  • 9
VaioIsBorn
  • 7,683
  • 9
  • 31
  • 28
  • See also http://stackoverflow.com/questions/1580332/stdpow-gives-a-wrong-approximation-for-fractional-exponents/1580344 – GManNickG Feb 27 '10 at 01:41
  • lol - integer division in c was my very first head scratcher too. No stack over flow then - just a humorless prof – Shane C. Mason Feb 27 '10 at 01:42

4 Answers4

31

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;
John Knoeller
  • 33,512
  • 4
  • 61
  • 92
0

You are using integer division, and 1/100 is always going to round down to zero in integer division.

If you wanted to do floating point division and simply truncate the result, you can ensure that you are using floating pointer literals instead, and d will be implicitly converted for you:

t = (int)((1.0 / 100.0) * d);
MikeP
  • 7,829
  • 33
  • 34
0

I think its because of

t = (1/100) * d;

1/100 as integer division = 0

then 0 * d always equals 0

if you do 1.0/100.0 i think it will work correctly

Eric
  • 19,525
  • 19
  • 84
  • 147
-3
t = (1/100) * d; 

That is always equals 0,you can do this

t=(1%100)*d 

and add it to 0

Smittey
  • 2,475
  • 10
  • 28
  • 35
Alex
  • 1