How to represent -infinity in programming

前端 未结 6 1727
野趣味
野趣味 2021-01-17 01:18

How can I represent -infinity in C++, Java, etc.?

In my exercise, I need to initialize a variable with -infinity to show that it\'s a very

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 01:53

    You cannot represent infinity with integers[1]. However, you can do so with floating point numbers, i.e., float and double.

    You list several languages in the tags, and they all have different ways of obtaining the infinity value (e.g., C99 defines INFINITY in math.h, if infinity is available with that implementation, while Java has POSITIVE_INFINITY and NEGATIVE_INFINITY in Float and Double classes). It is also often (but not always) possible to obtain infinity values by dividing floating point numbers by zero.

    [1] Excepting the possibility that you could wrap every arithmetic operation on your integers with code that checks for a special value that you treat as infinity. I wouldn't recommend this.

提交回复
热议问题