tags:

views:

308

answers:

4

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

A: 

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
+9  A: 

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
Or just use `d / 100.0`.
Joey
A: 

Try (1.0/100.0)*(float)d.

(1/100) * d is probably returning an int, which is then converted to a float. Instead you want to convert 1, 100, and d to floats, then do the operations.

Benjamin Manns
A: 

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