我遇到的问题是,将带符号的64位整数与等于max 的值进行比较,有时失败。以下是代码:
void MyClass::testAndDo(int64_t x, int64_t y) {
while (true) {
int64_t point = this->height == 0 ? 0 : int64_t(1) << (this->height - 1);
int64_t max = point - 1;
int64_t min = -point;
cout << "min: " << min << endl;
cout << "max: " << max << endl;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
cout << "min <= x : " << (min <= x) << endl;
cout << "x <= max: " << (x <= max) << endl;
cout << "min <= y : " << (min <= y) << endl;
cout << "y <= max: " << (y <= max) << endl;
cout << "INT64_MAX: " << INT64_MAX << endl;
cout << "x <= INT64_MAX: " << (x <= INT64_MAX) << endl;
cout << "max == INT64_MAX? " << (max == INT64_MAX) << endl;
if (min <= x && x <= max && min <= y &&
y <= max) {
break;
}
this->height += 1;
}
doStuff();
}
对于我给出的测试用例,x是-9223372036854775806(所以INT64_MIN + 2),y是-9223372036854775808(INT64_MIN)。
该函数中cout的输出如下:
min: -9223372036854775808
max: 9223372036854775807
x: -9223372036854775806
y: -9223372036854775808
min <= x : 1
x <= max: 0
min <= y : 1
y <= max: 0
INT64_MAX: 9223372036854775807
x <= INT64_MAX: 1
max == INT64_MAX? 1
所以我非常困惑 - x不小于max,但x IS小于INT64_MAX,max等于INT64_MAX。
任何人都可以解释发生了什么,或者我可能做错了什么?