计算C中百分比的结果不同

2 c formula

我有一个奇怪的问题.我开始阅读Let us 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;
Run Code Online (Sandbox Code Playgroud)

上面的输出如下:

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*
Run Code Online (Sandbox Code Playgroud)

但如果我修改百分比公式如下:percentage = aggregate/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)*
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么会发生这种情况,即使两者都使用相同的公式?

klu*_*utt 6

既然aggregate是一个int,(aggregate/500)*100就会产生一个int.改为(aggregate/500.0)*100aggregate/5.0

percentage= aggregate/5"工作" 的原因是纯粹的运气.它不会包含所有数字.当聚合为5的倍数时,它将给出正确的结果.