在C#整数运算中,a / b / c总是等于a /(b * c)吗? [英] In C# integer arithmetic, does a/b/c always equal a/(b*c)?

查看:1031
本文介绍了在C#整数运算中,a / b / c总是等于a /(b * c)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设a,b和c为非大正整数。 a / b / c是否始终与C#整数运算相等?/(b * c)?对我来说,在C#中它看起来像:

Let a, b and c be non-large positive integers. Does a/b/c always equal a/(b * c) with C# integer arithmetic? For me, in C# it looks like:

int a = 5126, b = 76, c = 14;
int x1 = a / b / c;
int x2 = a / (b * c);

所以我的问题是: x1 == x2 对于所有a,b和c?

So my question is: does x1 == x2 for all a, b and c?

推荐答案

\ 表示整数除法(两个 int s之间的C# / 运算符)并让 / 表示通常的数学师。然后,如果 x,y,z 正整数,我们忽略溢出

Let \ denote integer division (the C# / operator between two ints) and let / denote usual math division. Then, if x,y,z are positive integers and we are ignoring overflow,

(x \ y) \ z
    = floor(floor(x / y) / z)      [1]
    = floor((x / y) / z)           [2]
    = floor(x / (y * z))
    = x \ (y * z)

其中

a \ b = floor(a / b)

从行跳转[1] 到行 [2] 上面解释如下。假设你有两个整数 a b 和一个小数 f [0,1] 的范围内。很容易看到

The jump from line [1] to line [2] above is explained as follows. Suppose you have two integers a and b and a fractional number f in the range [0, 1). It is straightforward to see that

floor(a / b) = floor((a + f) / b)  [3]

如果在行 [1] 中,您确定 a = floor(x / y) f =(x / y) - floor(x / y),和 b = z ,然后 [3] 暗示 [1] [2] 相等。

If in line [1] you identify a = floor(x / y), f = (x / y) - floor(x / y), and b = z, then [3] implies that [1] and [2] are equal.

您可以将此证明推广为负整数(仍然忽略溢出),但我会把它留给读者来保持简单。

You can generalize this proof to negative integers (still ignoring overflow), but I'll leave that to the reader to keep the point simple.

关于溢出的问题 - 请参阅Eric Lippert的答案以获得一个很好的解释!他还在他的博客文章中采取了更严格的方法并回答了一些问题。应该看看你是否觉得我太手了。

On the issue of overflow - see Eric Lippert's answer for a good explanation! He also takes a much more rigorous approach in his blog post and answer, something you should look into if you feel I'm being too hand-wavy.

这篇关于在C#整数运算中,a / b / c总是等于a /(b * c)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆