在c++中设置int为Infinity

Setting an int to Infinity in C++

本文关键字:Infinity int 设置 c++      更新时间:2023-10-16

我有一个需要等于"无穷大"的int a。这意味着如果

int b = anyValue;

a>b总是为真。

c++中有什么特性可以使这成为可能吗?

整数本身是有限的。最接近的是将a设置为int的最大值:

#include <limits>
// ...
int a = std::numeric_limits<int>::max();

如果int是32位宽,则为2^31 - 1(或2 147 483 647)。

如果确实需要无穷大,请使用浮点数类型,如floatdouble。你可以用:

得到无穷大
double a = std::numeric_limits<double>::infinity();

整数是有限的,所以遗憾的是你不能将它设置为真正的无穷大。然而,你可以将它设置为int型的最大值,这意味着它将大于或等于任何其他int型,例如:

a>=b

总是为真。

你可以通过

#include <limits>
//your code here
int a = std::numeric_limits<int>::max();
//go off and lead a happy and productive life

这通常等于2,147,483,647

如果你真的需要一个真正的"无限"值,你必须使用双精度浮点数或浮点数。然后你可以这样做

float a = std::numeric_limits<float>::infinity();

关于数值限制的更多解释可以在这里找到

编码快乐!

注意:正如WTP所提到的,如果绝对有必要拥有一个"无限"的int型,那么您将不得不为int型编写一个包装类并重载比较操作符,尽管对于大多数项目来说这可能不是必需的。

这是给我以后的留言:

直接使用:(unsigned)!((int)0)

通过将所有位赋值为1(1),然后将其强制转换为unsigned

,在任何机器中创建可能的最大数字

更好
#define INF (unsigned)!((int)0)

然后在代码中使用INF

int本身是有限的;没有值能满足你的要求。

如果你想改变b的类型,你可以通过操作符覆盖来实现:

class infinitytype {};
template<typename T>
bool operator>(const T &, const infinitytype &) {
  return false;
}
template<typename T>
bool operator<(const T &, const infinitytype &) {
  return true;
}
bool operator<(const infinitytype &, const infinitytype &) {
  return false;
}

bool operator>(const infinitytype &, const infinitytype &) {
  return false;
}
// add operator==, operator!=, operator>=, operator<=...
int main() {
  std::cout << ( INT_MAX < infinitytype() ); // true
}

您也可以使用INT_MAX:

http://www.cplusplus.com/reference/climits/

相当于使用numeric_limits

我认为宏INFINITY是在header "<cmath>"。

定义如下:

#define INFINITY ((float)(1e+300 * 1e+300))

这是一个如此大的数字,以至于没有其他数字(至少在c++中)可以大于它。但显然,由于我们要转换为类型(int),它最多可以保存值2147483647。然后它会隐式地转换成那个值