整数溢出 C++ 即使使用“无符号长整型”也是如此

Integer overflow in C++ even when using `unsigned long`

本文关键字:长整型 C++ 溢出 整数 无符号      更新时间:2023-10-16

我试图用C++为我计算一个数字,但我得到了错误的答案。我认为这可能与数据类型有关?

我试图在乘法之前很久将所有数字转换为无符号,但结果是一样的。


#include <iostream>
using namespace std;
   int main()
   {
    unsigned int width = 8864;
    unsigned int height = 5288;
    unsigned int NImg = 50;
    unsigned long TotalBytes;
    TotalBytes = (width * height * NImg + 2 ) * 2;
    cout<<TotalBytes<<endl;
    }

TotalBytes 应该计算为 4687283204,但 c++ 代码给了我392315908。

谢谢

在您的

平台上,unsigned long也是 32 位,就像 unsigned int 一样。这还不足以存储计算结果。您必须使用 unsigned long long ,或者如果您愿意,您可以使用uint64_t

#include <iostream>
#include <cstdint>
using namespace std;
int main()
{
    uint64_t width = 8864;
    uint64_t height = 5288;
    uint64_t NImg = 50;
    uint64_t TotalBytes;
    TotalBytes = (width * height * NImg + 2 ) * 2;
    cout<<TotalBytes<<endl;
}

尝试使用大整数。您可以创建一个类或使用某人的库来实现它。例如,http://www.cplusplus.com/forum/general/108176/