VaioIsBorn VaioIsBorn -5 years ago 226
C Question

Division result is always zero

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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download