I need 开发者_Python百科to find a division of two integers and round it to next upper integer
e.g x=7/y=5 = 2; here x and y always greater than 0
This is my current code
int roundValue = x % y > 0? x / y + 1: x / y;
Is there any better way to do this?
You could use Math.Ceiling
... but that will require converting to/from double
values.
Another alternative is to use Math.DivRem
to do both parts at the same time.
public static int DivideRoundingUp(int x, int y)
{
// TODO: Define behaviour for negative numbers
int remainder;
int quotient = Math.DivRem(x, y, out remainder);
return remainder == 0 ? quotient : quotient + 1;
}
Try (int)Math.Ceiling(((double)x) / y)
All solutions looks too hard. For upper value of x/y, use this one
( x + y - 1 ) / y
dunno what's better way or how to define a better way (if in terms of performance you have to run tests to see which will be faster), but here's my solution:
int roundValue = x / y + Convert.ToInt32(x%y>0);
p.s.
still have to deal somehow with neg. numbers... IMO this is the simplest.
+0.5 will aways round to the higher.
Use ceil()
function.
It gives the upper value.
It's better to use MidpointRounding
from Math.Round
In your case:
Math.Round(value, MidpointRounding.AwayFromZero);
see more: https://learn.microsoft.com/ru-ru/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-double-system-midpointrounding)
精彩评论