在 C 中将 float +INF、-INF 和 NAN 转换为整数的结果是什么?
是否有任何标准指定应该输出什么?
例如这段代码:
#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!?!
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\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;
}
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 !?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 Paul 所说,它是未定义的:
来自 §6.3.1.4:
无穷大不是有限的,并且整数部分不能用整数类型表示,因此它是未定义的。
As Paul said, it's undefined:
From §6.3.1.4:
Infinity isn't finite, and the integral part can't be represented in an integral type, so it's undefined.