【问题标题】:Different results for calculating percentage in C在 C 中计算百分比的不同结果
【发布时间】:2021-10-28 16:52:15
【问题描述】:

我有一个奇怪的问题。我开始阅读 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;

上面的输出如下:

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

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

【问题讨论】:

    标签: c formula


    【解决方案1】:

    由于aggregate 是一个int,(aggregate/500)*100 将产生一个int。更改为(aggregate/500.0)*100aggregate/5.0

    percentage= aggregate/5“工作”的原因纯粹是运气。它不会与所有数字。当聚合为 5 的倍数时,它会给出正确的结果。

    另外,烧掉《Let us C》这本书。非常糟糕。

    【讨论】:

    • 嗨克鲁特,感谢您的回答。是的,它有效。自从我这样做以来已经太久了,我忘记了铸造是如何工作的。
    猜你喜欢
    • 1970-01-01
    • 2017-04-17
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    相关资源
    最近更新 更多