gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:41:00 25 4
gpt4 key购买 nike

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

例如这段代码:

#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)

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

关于c - 在 C 中将 float +INF、-INF 和 NAN 转换为整数的结果是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3986795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com