整数溢出 C++ 即使使用“无符号长整型”也是如此
Integer overflow in C++ even when using `unsigned long`
我试图用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/
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- JNI 日期值转换问题,在C++中获取不同的长整型值
- 将长整型值打印为带有前导零的十六进制
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 提升不良词法强制转换:将字符串转换为无符号长整型时,无法将源类型值解释为目标
- 将最小值整数转换为无符号长整型
- 如何将小端格式的QByteArray转换为无符号长整型
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- 环礁和(长整型)的区别?
- 将逗号格式化为长整型整数
- 如何将长整型传递给 itoa 函数?
- 是否存在将长整型转换为指针有效的情况
- 在 C++ 中创建一对长整型和矢量时出现编译错误
- 当我使用长整型时,我的代码不起作用,它与 int 一起工作得很好
- 将字符串中以十六进制形式存储的负长整型值转换为 C++ 中的长整型变量
- 为什么当我们把变量"u"的数据类型从长整型更改为整型时,模幂会出错?
- 错误:请求从 std::chrono::time_point 浮点数转换为非标量类型长整型
- 如何以优雅高效的方式将无符号/有符号整数/长整型转换为 C 字符串?
- 将 BYTE 数组转换为无符号长整型