gpt4 book ai didi

c++ - 存在溢出时的整数运算

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:19 25 4
gpt4 key购买 nike

按照以下规则处理两个 32 位整数值 A 和 B,得到 32 位整数 C 和 D。哪些规则是可逆的?即在所有条件下给定 c 和 D 是否有可能获得 A 和 B?

一个。 C = (int32)(A+B), D = (int32)(A-B)

B. C = (int32)(A+B), D= (int32)((A-B)>>1)

C. C = (int32)(A+B), D = B

D. C = (int32)(A+B), D = (int32)(A+2*B)

E. C = (int32)(A*B), D = (int32)(A/B)

关于整数运算的几个问题。模加法形成称为 阿贝尔群 的数学结构。 符号加法怎么样?它也是可交换的(这就是“阿贝尔”部分出现的地方)和结合的,这是否形成了一个 阿贝尔群

鉴于整数加法是可交换和结合的,C 显然是正确的,因为我们可以通过 (A+(B-B)) 检索 A。 D 怎么样? 我们可以假设 2 * B = B + B st. B = A+B+B-(A+B)?

而且乘法比较复杂,但是我知道如果出现溢出就不能取到A。

最佳答案

这是 5 [expr] 第 4 段的引述:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

3.9.1 [basic.fundamental] 第 4 段中定义了使无符号整数溢出起作用的原因:

Unsigned integers shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

基本上这就是说在使用有符号整数运算时不应溢出。如果你这样做,所有的赌注都没有了。这意味着有符号整数在 C++ 中不构成阿贝尔群。

关于c++ - 存在溢出时的整数运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com