gpt4 book ai didi

C++ 大数溢出检测(unsigned long long)

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:06 26 4
gpt4 key购买 nike

我正在处理大整数(unsigned long long)并且需要防止溢出情况。无论是否确实存在,代码都会抛出异常:

try
{
unsigned long long y = std::numeric_limits<unsigned long long>::max() - 2;
unsigned long long z = 1;
int size = - 1;
if((y+z) ^ y < 0) //If y+z causes overflow its sign will be changed => y and (y+z) will have opposite signs
throw std::overflow_error("overflow of y+z");
//int* myarray= new int[size]; VS Debug Library catches it earlier than catch()
printf("%d\n", y*(y+z));
}
catch(exception& e)
{
cout << e.what() << endl;
}

由于它已经是最大的数据类型(64 位),因此没有提升到更大的空间。

新代码:

try
{
unsigned long long int y = std::numeric_limits<unsigned long long int>::max() - 2;
unsigned long long int z = std::numeric_limits<unsigned long long int>::max() / 2;
unsigned long long delta = std::numeric_limits<unsigned long long int>::max() - y;
int size = - 1;
if(z > delta) //If y+z causes overflow its sign will be changed => y and (y+z) will have opposite signs
throw std::overflow_error("overflow of y+z");
//int* myarray= new int[size]; VS Debug Library catches it earlier than catch()
printf("%d\n", (y+z));
}
catch(exception& e)
{
cout << e.what() << endl;
}

最佳答案

y < 0将始终为假,任何 xor 0 将始终是那个东西(您是否错过了 < 的评估优先级高于 ^ ?)。

因此除非x + y国防部 <the max value> happens to equal 0, you will throw (and probably appears to always throw in practice unless you contrived specific inputs).

Perhaps what you meant to do was something like this: if((std::numeric_limits<unsigned long long>::max() - y) < z) throw ...;

关于C++ 大数溢出检测(unsigned long long),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29778700/

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