简体   繁体   English

C#中的整数除法(对于负数)

[英]Integer division rounding down in C# (for negatives)

Is there any way to perform integer dividing in C# (without float or decimal, I need to keep this one very fast) that rounds down the number? 有什么方法可以在C#中执行整数除法(没有浮点数或小数,我需要非常快地保持这一位数)以舍入数字?

The default division just discards fraction argument. 默认除法只是丢弃小数参数。 Consider: 考虑:

 1 / 2 = 0 // That is correct
-1 / 2 = 0 // ... but I want to get (-1) here!

My division will take both positive and negative numbers for dividor. 我的除法将同时使用正数和负数作为除数。 I need not to employ if , as branching will be too costly (the operation will be run very frequently in realtime game engine)... 我不需要雇用if ,因为分支的成本太高(操作将在实时游戏引擎中非常频繁地运行)...

If you want to divide a by b : 如果要用a除以b

The approach which won't fail because of overflow: 不会因溢出而失败的方法:

int res = a / b;
return (a < 0 && a != b * res) ? res - 1 : res;

The following approaches may possibly fail because of negative overflow. 由于负溢出,以下方法可能会失败。

int mod = a % b;
if (mod < 0) {
  mod += b;
}
return (a - mod) / b;

A mess with mod += b because a % b can be negative. mod += b会造成混乱,因为a % b可能为负。 A shorter way: 较短的方法:

return (a - (a % b + b) % b) / b;

And more clear one: 还有更清楚的一个:

return a >= 0 ? a / b : (a - b + 1) / b;

Dividing by 2 is a simple bitwise right-shift. 除以2是简单的按位右移。 After @elgonzo's (now deleted) mention of the properties of C#'s rightshift, I decided to have a look how it works, and it seems to do exactly what you want: 在@elgonzo(现在已删除)提到C#右移的属性之后,我决定看看它是如何工作的,它似乎完全可以满足您的要求:

var result = number >> 1;

This gives the following results: 得到以下结果:

11 -> 5 11-> 5
10 -> 5 10-> 5
2 -> 1 2-> 1
1 -> 0 1-> 0
-1 -> -1 -1-> -1
-2 -> -1 -2-> -1
-32 -> -16 -32-> -16
-33 -> -17 -33-> -17

int.MaxValue and MinValue also work. int.MaxValue和MinValue也可以。

Performance-wise, this seems to be almost twice as fast as the currently accepted answer that uses modulo operators. 在性能方面,这似乎是当前接受的使用模运算符的答案的速度几乎快一倍。 Dividing (the same) 100000000 random numbers costs 2.17 seconds on my machine using a simple shift, while using the version with modulo's takes between 3.1 and 4.0 seconds. 在我的机器上,通过简单的移位将100000000个随机数相除(相同)将花费2.17秒,而使用模数的版本将花费3.1至4.0秒。

The branched versions seem to perform just about the same as the modulo version: significantly slower than the simple rightshift. 分支版本的性能似乎几乎与模版本相同:比简单的右移明显慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM