2017-10-23 21 views
2

私は奇妙な質問があります。私はを読んで始めました.Cに行きましょう。 私は以下のコードをpercentage変数に渡すと出力として0が得られますが、式を変更するとそれはできません。なぜ誰かが説明できますか?Cのパーセンテージを計算するための異なる結果

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

誰かが同じフォーミュラを使用しているにもかかわらず、なぜこれが起こるのか説明してください。

答えて

6

aggregateがintであるため、(aggregate/500)*100はintを生成します。 (aggregate/500.0)*100またはaggregate/5.0に変更

理由「percentage= aggregate/5」は純粋に幸運です。それはすべての数字ではありません。集計が5の倍数である場合、正しい結果が得られます。

+0

こんにちはKlutt、ありがとうございます。はい、それは動作します。私はこれをやったので、私はあまりにも長すぎると私は鋳造の作品が忘れてしまった。 –

関連する問題