我有一个奇怪的问题。我开始阅读让我们C 并遇到一种情况。
当我给出以下代码percentage
变量时,我得到0
作为输出,但是当我修改公式时,它不会这样做。有人可以解释原因吗?
int m1,m2,m3,m4,m5,aggregate;
float percentage;
printf("Please enter marks of the student in 5 subjects : \n");
scanf("%d %d %d %d %d",&m1,&m2,&m3,&m4,&m5);
aggregate = m1+m2+m3+m4+m5;
percentage= (aggregate/500)*100;
上面的输出如下:
Please enter marks of the student in 5 subjects :
50 50 50 50 50
The aggregate of marks obtained by the student is : 250
The percentage of marks obtained by the student is : 0.000000*
但如果我修改百分比公式如下: 百分比=聚合/ 5;
我得到了正确的输出。
Please enter marks of the student in 5 subjects :
50 50 50 50 50
The aggregate of marks obtained by the student is : 250
The percentage of marks obtained by the student is : 50.000000
RUN SUCCESSFUL (total time: 6s)*
有人可以解释为什么会发生这种情况,即使两者都使用相同的公式吗?
答案 0 :(得分:6)
由于aggregate
是一个int,(aggregate/500)*100
将产生一个int。更改为(aggregate/500.0)*100
或aggregate/5.0
percentage= aggregate/5
“工作原因”是纯粹的运气。它不会包含所有数字。当聚合为5的倍数时,它将给出正确的结果。