在 C++ 中将 int 设置为 Infinity
我有一个 int a
需要等于“无穷大”。这意味着如果
int b = anyValue;
a>b
始终为 true。
C++ 是否有任何功能可以使这成为可能?
I have an int a
that needs to be equal to "infinity". This means that if
int b = anyValue;
a>b
is always true.
Is there any feature of C++ that could make this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(6)
肥爪爪2024-12-30 17:59:32
整数是有限的,所以遗憾的是你不能将它设置为真正的无穷大。
但是,您可以将其设置为 int 的最大值,这意味着它将大于或等于任何其他 int,即:
a>=b
始终为 true。
您可以通过以下方式执行此操作
#include <limits>
//your code here
int a = std::numeric_limits<int>::max();
//go off and lead a happy and productive life
:This will通常等于2,147,483,647
如果您确实需要一个真正的“无限”值,则必须使用双精度或浮点数。然后您可以简单地执行此操作。
float a = std::numeric_limits<float>::infinity();
可以在此处找到数字限制的其他说明,
祝您编码愉快!
注意:正如 WTP 提到的,如果绝对需要有一个“无限”的 int,则必须为 int 编写一个包装类并重载比较运算符,尽管这对于大多数项目来说可能不是必需的。
意中人2024-12-30 17:59:32
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
}
请持续率性2024-12-30 17:59:32
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
整数本质上是有限的。您可以获得的最接近的结果是将
a
设置为int
的最大值:这将是
2^31 - 1
(或2 147 483 647
) 如果int
在您的实现中是 32 位宽。如果您确实需要无穷大,请使用浮点数类型,例如
float
或double
。然后你可以通过以下方式获得无穷大:Integers are inherently finite. The closest you can get is by setting
a
toint
's maximum value:Which would be
2^31 - 1
(or2 147 483 647
) ifint
is 32 bits wide on your implementation.If you really need infinity, use a floating point number type, like
float
ordouble
. You can then get infinity with: