在 C + + 中将 int 设置为 Infinity

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

int b = anyValue;

a>b总是正确的。

C + + 有什么特性可以让这一切成为可能吗?

296708 次浏览

整数本质上是有限的。最接近的方法是将 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本质上是有限的; 没有值可以满足您的需求。

但是,如果您愿意更改 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 的最大值,这意味着它将大于或等于任何其他 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

如果您确实需要一个真正的“无限”值,那么就必须使用 double 或 float。然后你就可以这么做了

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

数值限制的其他解释可以找到 给你

编码愉快!

注意: 正如 WTP 所提到的,如果绝对需要一个“无限”的 int,那么就必须为 int 编写一个包装类,并重载比较运算符,尽管对于大多数项目来说这可能不是必需的。

你也可以使用 INT _ MAX:

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

它等效于使用 numeric _ limit。

这是给我未来的信息:

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

它通过将所有位分配给1(1) ,然后将其强制转换为无符号数,从而在任何机器中创建尽可能大的数

那就更好了

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

然后在代码中使用 INF

我认为一个宏 INFINITY是定义在标题“ <cmath>”。

它的定义如下,

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

这是一个如此之大的数字,没有其他数字 (至少在 c + + 中)可以大于它。但是很明显,因为我们正在转换到一个类型 (int),它在最大值时可以保存一个值 2147483647。那么它就会隐式地转换成那个值。