我正尝试在21天(第六版)中使用Sams Teach Yourself C ++再次学习C ++。我试图非常彻底地完成它,以确保我理解每一章(尽管我已经熟悉C语法语言)。

在第5章(清单5.2)的开头附近,有一点关于无符号整数溢出。根据他们的例子,我这​​样写:

#include <iostream>

int main () {
    unsigned int bignum = 100;
    unsigned int smallnum = 50;
    unsigned int udiff;
    int diff;
    udiff = bignum - smallnum;
    std::cout << "Difference (1) is " << udiff << "\n";
    udiff = smallnum - bignum;
    std::cout << "Difference (2) is " << udiff << "\n";
    diff = bignum - smallnum;
    std::cout << "Difference (3) is " << diff << "\n";
    diff = smallnum - bignum;
    std::cout << "Difference (4) is " << diff << "\n";
    return 0;
}


这给出了以下输出,这对我来说并不奇怪:

Difference (1) is 50
Difference (2) is 4294967246
Difference (3) is 50
Difference (4) is -50


如果我更改程序,使声明bignum的行改为读取unsigned int bignum = 3000000000;,则输出改为

Difference (1) is 2999999950
Difference (2) is 1294967346
Difference (3) is -1294967346
Difference (4) is 1294967346


这些中的第一个显然很好。数字1294967346的解释是1294967346恰好是2^32 - 3000000000。我不明白为什么第二行不显示1294967396,原因是smallnum贡献了50。

我无法解释的第三和第四行。这些结果如何产生?

编辑:对于第三行-仅通过找到适合带符号的int允许的值范围的模2^32的解决方案,就可以得出此结果吗?

最佳答案

2 ^ 32-3000000000 = 1294967296(!)

关于c++ - 减法上的整数溢出的种类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3982787/

10-12 06:28