Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

math - What is the result of casting float +INF, -INF, and NAN to integer in C?

Does any standard specifies what should be the output?

For example this code:

#include <stdio.h>
#include <math.h>

int main(int argc, char** argv) {
  float a = INFINITY;
  float b = -INFINITY;
  float c = NAN;

  printf("float %f %f %f
", a, b, c); 
  printf("int %d %d %d
", (int) a, (int) b, (int) c); 
  printf("uint %u %u %u
", (unsigned int) a, (unsigned int) b, (unsigned int) c); 
  printf("lint %ld %ld %ld
", (long int) a, (long int) b, (long int) b); 
  printf("luint %lu %lu %lu
", (unsigned long int) a, (unsigned long int) b, (unsigned long int) c); 

  return 0;
}

Compiled on gcc version 4.2.1 (Apple Inc. build 5664) Target: i686-apple-darwin10

Outputs:

$ gcc test.c && ./a.out 
float inf -inf nan
int -2147483648 -2147483648 -2147483648
uint 0 0 0
lint -9223372036854775808 -9223372036854775808 -9223372036854775808
luint 0 9223372036854775808 9223372036854775808

Which is quite weird. (int)+inf < 0 !?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Paul said, it's undefined:

From §6.3.1.4:

6.3.1.4 Real ?oating and integer

When a ?nite value of real ?oating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is unde?ned.50)

Infinity isn't finite, and the integral part can't be represented in an integral type, so it's undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...