C#中如何对数字进行四舍五入

4
我已经创建了一个认证系统,用户可以参加考试。在批改考试时,我希望返回一个百分比数字。因此,我正在将正确答案的数量除以考试问题的总数,并乘以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

提前感谢您的帮助。


1
只是猜测,尝试在执行除法之前将correctQuestionsForAttempt.Count转换为(double)。 - George
6个回答

6

我相信你正在寻找Math.Ceiling函数。

decimal number = 43.4M;
int roundedNumber = (int) Math.Ceiling(number);

这将会给你44


6

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

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

4

You can simply do Math.Ceiling(43.4)


0

您想要使用 Math.Ceiling() - 请参见这里

在您的上下文中,它将被用作如下:

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

0

在强制转换之前,只需将您的数字加上0.5即可


0

这不是一个四舍五入的问题,而是一个数字类型的问题。

集合的 .Count 属性(我假设这就是 correctQuestionsForAttemptdvAttemptQuestions)是一个 int。将一个 int 除以另一个 int 将会得到另一个 int,没有任何小数位。像这样截断小数位会给人一种向下取整的感觉。结果是你调用了 decimal.Round 来尝试对一个已经是整数的东西进行四舍五入。

如果在除以总数之前将正确的数量乘以100,这个问题应该就可以解决了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接