用C#舍入数字[复制](Rounding a number using C# [duplicate])

编程入门 行业动态 更新时间:2024-10-27 10:22:44
用C#舍入数字[复制](Rounding a number using C# [duplicate])

这个问题在这里已经有了答案:

如何在c# 2中回答

我创建了一个用户可以参加考试的认证系统。 在标记考试时,我希望返回一个百分比数字。 所以我正在考虑正确的问题数字,除以考试中的问题数量并乘以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

提前谢谢了。

This question already has an answer here:

How to round up in c# 2 answers

I have created an accreditation system where a user can take exams. On marking the exam i wish to return a percentage figure. So i am taking the correct questions figure, dividing it by the number of questions in the exam and multiplying it by 100.

My issue is rounding the number up. So if the figure returned was 76.9 my code is giving me 76 where rounded up it should be 77 etc.

this is the line of code i that is working this out...

int userScorePercentageConvert = (int)decimal.Round((correctQuestionsForAttempt.Count / dvAttemptQuestions.Count * 100), MidpointRounding.AwayFromZero);

Can anyone tell me how to amend this piece of code so it is rounding correctly

i.e. 43.4 = 44 | 67.7 = 68 | 21.5 = 22

Many thanks in advance.

最满意答案

问题是你在这里使用整数除法 :

(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);

The problem is that you're using integer division right here:

(correctQuestionsForAttempt.Count / dvAttemptQuestions.Count * 100)

With integer division in a case like this, you'll always end up with 0 or 100.

This will work:

(100.0 * correctQuestionsForAttempt.Count / dvAttemptQuestions.Count)

Also, from what you describe, you want a Ceiling function (think of it as rounding up), not a Round (rounding to the nearest integer, with options on how to round midpoint values).

int userScorePercentageConvert = (int)Math.Ceiling(100.0 * correctQuestionsForAttempt.Count / dvAttemptQuestions.Count);

更多推荐

本文发布于:2023-08-07 17:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465495.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   Rounding   duplicate   number

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!