将float INF,-INF和NAN转换为C中的整数的结果是什么?

前端之家收集整理的这篇文章主要介绍了将float INF,-INF和NAN转换为C中的整数的结果是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有什么标准规定应该输出什么?

例如这个代码

#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\n",a,b,c); 
  printf("int %d %d %d\n",(int) a,(int) b,(int) c); 
  printf("uint %u %u %u\n",(unsigned int) a,(unsigned int) b,(unsigned int) c); 
  printf("lint %ld %ld %ld\n",(long int) a,(long int) b,(long int) b); 
  printf("luint %lu %lu %lu\n",(unsigned long int) a,(unsigned long int) b,(unsigned long int) c); 

  return 0;
}

编译在gcc 4.2.1版(Apple Inc. build 5664)目标:i686-apple-darwin10

输出

$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

这是很奇怪的(int)inf < 0!?

解决方法

正如保罗所说,这是不明确的:

从§6.3.1.4:

6.3.1.4 Real floating and integer

When a finite value of real floating 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 undefined.50)

无穷大不是有限的,整体部分不能以积分形式表示,所以它是未定义的.

原文链接:https://www.f2er.com/css/214745.html

猜你在找的CSS相关文章