How to generate NaN, -Infinity and +Infinity in ANSI C?

后端 未结 4 1873
南方客
南方客 2020-12-05 03:53

I use ANSI C89 (not C++), and I want to generate NaN, -Infinity and +Infinity.

Is there any standard way (eg. standard macro)?

4条回答
  •  一个人的身影
    2020-12-05 04:40

    I don't know if this is standard or portable, but here's a start:

    jcomeau@intrepid:/tmp$ cat test.c; make test; ./test
    #include 
    int main() {
     printf("%f\n", 1.0 / 0);
     printf("%f\n", -1.0 / 0);
     printf("%f\n", 0.0 / 0);
     return 0;
    }
    cc     test.c   -o test
    test.c: In function ‘main’:
    test.c:3: warning: division by zero
    test.c:4: warning: division by zero
    test.c:5: warning: division by zero
    inf
    -inf
    -nan
    

    Strangely enough, I can't get positive NaN using this naive approach.


    Also see this: http://www.gnu.org/s/hello/manual/libc/Infinity-and-NaN.html

提交回复
热议问题