可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
I got this C code.
#include 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) ?
回答1:
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;
回答2:
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);
回答3:
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
回答4:
t = (1/100) * d;
That is always equals 0,you can do this
t=(1%100)*d
and add it to 0