对数字进行四舍五入
var output = Convert.ToDecimal(amount / 4);
labelOutput.Text = "You need: " + System.Math.Round(output,0);
此代码是游戏计算器的一部分
“金额”是用户想要制作的金额,要制作单个项目,您需要 4 件 (/4),
例如:
多少?:20
20 / 4 = 5
“你需要 5 件,
但当我输入 21 时,仍然显示 5 件,但用户需要 6 件才能制作 21 件商品(每件 4 件) item)
当输入为 21 - 23 时,如何将输出四舍五入为 6 而不是 5?
(抱歉,如果我解释得不够好)
var output = Convert.ToDecimal(amount / 4);
labelOutput.Text = "You need: " + System.Math.Round(output,0);
this code is part of a calculator for a game
"amount" is how much the user wants to make, and to make a single item, you need 4 pieces ( / 4)
for instance:
how much?: 20
20 / 4 = 5
"you need 5 pieces
but when i enter 21, still says 5 pieces but the users needs 6 pieces to make 21 items (4 for every item)
How can i round up the output to make it say 6 instead of 5 when the input is, in this case, 21 - 23?
(sorry if I didn't explain it good enough)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用Math.Ceiling
Use
Math.Ceiling
要给出完整的答案(结合上述内容):
Ceiling< /code>
而不是
Round
假设
amount
是一个整数,您需要让除法运算中的一个值是非整数(float
/double< /code> 或
decimal
,我在示例中选择了decimal
,并带有m
后缀)。如果除法运算的两个部分都是整数类型,您将得到一个整数答案(删除余数)。然后,您可以调用
Ceiling
来获取等于或大于output
的最小整数值(而不是Round
,后者给出最接近的整数值 <代码>输出)。To give a complete answer (combining the above):
Ceiling
instead ofRound
Assuming that
amount
is an integer, you need to have one of the values in your division operation be non-integral (eitherfloat
/double
ordecimal
, I've opted fordecimal
in my example with them
suffix). If both parts of the division operation are integral types, you'll get an integral answer (dropping the remainder).You then call
Ceiling
to get the smallest integer value equal to or greater thanoutput
(rather thanRound
, which gives the closest integer value tooutput
).round 函数将数字四舍五入到最接近的数字。
对于四舍五入,您必须使用 Math.Ceiling()
如果需要向下舍入,则必须使用 Math.Floor()
The round function rounds the number to the nearest one.
For a round up you have to use Math.Ceiling()
If you need to round down you have to use Math.Floor()
假设“amount”是整数类型,那么这里的问题是您在第一行中执行整数(整数)除法。
尝试将第一行更改为: var output = Convert.ToDecimal(amount) / 4.0;
Assuming that 'amount' is an integer type, then the problem here is that you are a performing an integer (whole-number) division right in your first line.
Try changing the first line to:
var output = Convert.ToDecimal(amount) / 4.0;
Round
会将数字四舍五入 - 您想要的是始终向上舍入,您可以使用Ceiling
函数获得Round
will round the number off -- what you want is to always round up, which you can get by using theCeiling
function请改用 Math.Ceiling(amount / 4) 。
Use
Math.Ceiling(amount / 4)
instead.也许有点难看:
var output = Convert.ToDecimal((amount+3) / 4);
如果您的金额紧邻 MaxValue,则存在一种边缘情况,此时此代码可能会中断,具体取决于您的情况分母。A bit ugly, perhaps:
var output = Convert.ToDecimal((amount+3) / 4);
There's an edge case if your amount is right next to MaxValue where this code could break, depending on your denominator.