developer tip

C ++에서 int를 Infinity로 설정

optionbox 2020. 8. 19. 07:58
반응형

C ++에서 int를 Infinity로 설정


나는 int a"무한대"와 같아야 하는 것을 가지고 있다. 이것은

int b = anyValue;

a>b 항상 사실입니다.

이를 가능하게하는 C ++의 기능이 있습니까?


정수는 본질적으로 유한합니다. 가장 가까운 것은 의 최대 값 으로 설정 a하는 것입니다 int.

#include <limits>

// ...

int a = std::numeric_limits<int>::max();

어느 것 2^31 - 1(또는 2 147 483 647경우) int구현에 32 비트입니다.

당신이 경우 정말 무한대 필요, 부동 소수점 숫자 형식을 사용 같은 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과 같습니다.

진정한 "무한"값이 정말로 필요한 경우 double 또는 float를 사용해야합니다. 그런 다음 간단히 할 수 있습니다.

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

숫자 제한에 대한 추가 설명은 여기 에서 찾을 수 있습니다.

행복한 코딩!

참고 : WTP가 언급했듯이 "무한"인 int가 반드시 필요한 경우 int에 대한 래퍼 클래스를 작성하고 비교 연산자를 오버로드해야하지만 대부분의 프로젝트에서는 필요하지 않을 수 있습니다.


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를 사용하는 것과 같습니다.


이것은 나에게 미래에 대한 메시지입니다.

Just use: (unsigned)!((int)0)

It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned

Even better

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

And then just use INF in your code


int min and max values

Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807

i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64

if you always want a to be grater that b why do you need to check it? just set it to be true always

참고URL : https://stackoverflow.com/questions/8690567/setting-an-int-to-infinity-in-c

반응형