我有一个int a
需要等于"无限".这意味着如果
int b = anyValue;
Run Code Online (Sandbox Code Playgroud)
a>b
总是如此.
是否有任何C++功能可以实现这一目标?
Eti*_*tel 116
整数本质上是有限的.你可以得到的最接近的是设置a
为int
最大值:
#include <limits>
// ...
int a = std::numeric_limits<int>::max();
Run Code Online (Sandbox Code Playgroud)
如果你的实现是32位宽,那将是2^31 - 1
(或2 147 483 647
)int
.
如果您确实需要无穷大,请使用浮点数类型,如float
或double
.然后你可以得到无穷大:
double a = std::numeric_limits<double>::infinity();
Run Code Online (Sandbox Code Playgroud)
Dan*_*zer 61
整数是有限的,所以遗憾的是你无法将它设置为真正的无穷大.但是,您可以将其设置为int的最大值,这意味着它将大于或等于任何其他int,即:
a>=b
Run Code Online (Sandbox Code Playgroud)
总是如此.
你会这样做的
#include <limits>
//your code here
int a = std::numeric_limits<int>::max();
//go off and lead a happy and productive life
Run Code Online (Sandbox Code Playgroud)
这通常等于2,147,483,647
如果你真的需要一个真正的"无限"值,你必须使用double或float.然后你就可以做到这一点
float a = std::numeric_limits<float>::infinity();
Run Code Online (Sandbox Code Playgroud)
可在此处找到数字限制的其他说明
快乐的编码!
注意:正如WTP所提到的,如果绝对需要一个"无限"的int,你必须为int编写一个包装类并重载比较运算符,尽管对于大多数项目来说这可能不是必需的.
bdo*_*lan 12
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
}
Run Code Online (Sandbox Code Playgroud)
这是对我未来的信息:
只需使用: (unsigned)!((int)0)
它通过将所有位分配为 1(一个),然后将其强制转换为无符号数,从而在任何机器中创建最大可能的数字
甚至更好
#define INF (unsigned)!((int)0)
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中使用 INF
我认为宏INFINITY
是在标题“ <cmath>
”中定义的。
它的定义如下,
#define INFINITY ((float)(1e+300 * 1e+300))
Run Code Online (Sandbox Code Playgroud)
这是一个如此大的数字,以至于没有其他数字(至少在 C++ 中)可以大于它。但显然,因为我们要转换为类型( int
),它最多可以保存一个值2147483647
。那么它就会隐式转换为该值。