我创建了一个认证系统,用户可以在其中参加考试。在标记考试时,我希望返回一个百分比数字。因此,我采用了正确的试题数字,将其除以考试中的试题数目,然后乘以100。
我的问题是四舍五入。因此,如果返回的数字是76.9,我的代码给了我76,四舍五入应该是77,依此类推。
这是我正在解决的代码行...
int userScorePercentageConvert = (int)decimal.Round((correctQuestionsForAttempt.Count / dvAttemptQuestions.Count * 100), MidpointRounding.AwayFromZero);
谁能告诉我如何修改这段代码,以便正确舍入
即43.4 = 44 | 67.7 = 68 | 21.5 = 22
提前谢谢了。
问题是您在这里使用整数除法:
(correctQuestionsForAttempt.Count / dvAttemptQuestions.Count * 100)
在这种情况下使用整数除法,您总是以0或100结尾。
这将起作用:
(100.0 * correctQuestionsForAttempt.Count / dvAttemptQuestions.Count)
另外,根据您的描述,您需要一个Ceiling
函数(将其视为四舍五入),而不是一个Round
(四舍五入到最接近的整数,并具有如何舍入中点值的选项)。
int userScorePercentageConvert = (int)Math.Ceiling(100.0 * correctQuestionsForAttempt.Count / dvAttemptQuestions.Count);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句