gpt4 book ai didi

C++11 abs() of numeric_limits::min();

转载 作者:搜寻专家 更新时间:2023-10-31 00:33:03 26 4
gpt4 key购买 nike

我正在运行以下

测试.cpp

#include <iostream>
#include <limits>
#include <cstdlib>
using namespace std;

int main(int argc, char** argv) {
long value = numeric_limits<long>::min();
value = abs(value);
cout << value << endl;
}

根据我在哪台计算机上编译和运行程序,我会得到不同的结果。

要么我得到:

abs(numeric_limits<long>::min())

或者我得到:

numeric_limits<long>::min()

在后一种情况下,似乎没有执行 abs()。我想知道是什么导致了这种差异以及我应该如何适应它。我应该以不同的方式计算 abs() 吗?

最佳答案

查看 std::abs 的引用告诉我们出了什么问题:

Computes the absolute value of an integer number. The behavior is undefined if the result cannot be represented by the return type.

所以任何事情都有可能发生。它甚至在下面解释了对有符号整数使用 2 的补码的系统的情况:

Notes

In 2's complement systems, the absolute value of the most-negative value is out of range, e.g. for 32-bit 2's complement type int, INT_MIN is -2147483648, but the would-be result 2147483648 is greater than INT_MAX, which is 2147483647.

如果您对实际的标准引用感兴趣,请参阅第 7.20.6/7.22.6 节中的 C99/C11 standard分别,因为 C++ 只引用 C 标准中的函数 <cstdlib> (有一些额外的重载)。

关于C++11 abs() of numeric_limits<long>::min();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809537/

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