在c++中设置int为Infinity
Setting an int to Infinity in C++
我有一个需要等于"无穷大"的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
)。
如果确实需要无穷大,请使用浮点数类型,如float
或double
。你可以用:
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
。然后它会隐式地转换成那个值
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- 长 长 int 不要 长 int 好
- C++程序在循环后给出奇怪的int值
- 如何计算数据类型的范围,例如int
- 为什么 numeric_limits<int>::max() 是 <int>> numeric_limits::infinity()?
- 在c++中设置int为Infinity