本文介绍了被除法四舍五入咬了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现以下代码:

Why does the following code:

Console.WriteLine(String.Format("{0:C0}", 2170/ 20));

收益$109",同时做

yield "$109", while doing

Console.WriteLine(Math.Round(2170 / 20));

给我 108?

我怎样才能得到 2170/20 给我 109?

How can I get 2170 / 20 give me 109?

推荐答案

当您划分为整数类型的值时,例如 217020,运行时执行整数除法并丢弃(截断)小数.

When you divide to values of integral type, such as 2170 and 20, the runtime performs an integer division and discards (truncates) the decimal.

如果您将操作数之一更改为 floatdoubledecimal(例如,2170.0/20code> 或 2170/20m),它将执行浮点除法,如您所料.

If you change one of the operands to a float, double, or decimal (eg, 2170.0 / 20, or 2170 / 20m), it will perform a floating-point division, as you would expect.

因此,您需要将其更改为

Therefore, you need to change it to

Console.WriteLine(Math.Round(2170.0 / 20));


编辑

像这样:

Math.Round(2170m / 20, MidpointRounding.AwayFromZero)

这篇关于被除法四舍五入咬了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 20:52