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

发布于 2024-09-29 02:27:55 字数 948 浏览 0 评论 0原文

是否有任何标准指定应该输出什么?

例如这段代码:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长亭外,古道边 2024-10-06 02:27:55

正如 Paul 所说,它是未定义的:

来自 §6.3.1.4:

6.3.1.4 实数浮点数和整数

当实浮点类型的有限值为
转换为整数类型 other
比_Bool小数部分为
被丢弃(即该值为
截断为零)。如果值
的积分部分不能是
由整数类型表示,
行为未定义。50)

无穷大不是有限的,并且整数部分不能用整数类型表示,因此它是未定义的。

As Paul said, it's undefined:

From §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)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文