c - 1/(1.0/0.0) 在 C 中计算为零

标签 c operator-precedence

在 C 语言中计算以下表达式时,输出为零而不是无穷大。但根据 C 运算符优先级规则,输出应该是无穷大。

double a=1/(1.0/0.0);
printf("a : %.18le\n", a);

请解释一下 gcc 编译器如何评估它?

最佳答案

C 标准没有规定 double 如何处理 NaN 和 Inf 数字,但是对于 gcc,其行为由严格模式下的 IEEE 754 规定:https://en.wikipedia.org/wiki/IEEE_754

摘自那篇文章:

The standard defines five exceptions, each of which returns a default value and has a corresponding status flag that (except in certain cases of underflow) is raised when the exception occurs. No other exception handling is required, but additional non-default alternatives are recommended (see below).

The five possible exceptions are:

  • Invalid operation: mathematically undefined, e.g., the square root of a negative number. Returns qNaN by default.

  • Division by zero: an operation on finite operands gives an exact infinite result, e.g., 1/0 or log(0). Returns ±infinity by default.

  • Overflow: a result is too large to be represented correctly (i.e., its exponent with an unbounded exponent range would be larger than emax). Returns ±infinity by default for the round-to-nearest mode.
  • Underflow: a result is very small (outside the normal range) and is inexact. Returns a subnormal or zero by default.
  • Inexact: the exact (i.e., unrounded) result is not representable exactly. Returns the correctly rounded result by default.

但是,在某些平台上,IEEE 754 兼容的浮点单元不可用,您应该强制使用软件浮点库或查阅平台手册以了解发生的情况。例如,arm 的 fpu 有一个“RunFast”模式,该模式会禁用严格合规性。

一些更多信息:Do any real-world CPUs not use IEEE 754?

关于c - 1/(1.0/0.0) 在 C 中计算为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50176461/

相关文章:

凯撒密码不适用于空格

受控嵌套循环

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - 使用引擎生成随机数

c - 将动态结构传递给函数时出现段错误(核心转储)

c - 为什么我可以修改C中的const指针?

python - 生成器和文件

c++ - 在一条指令中声明更多指针的运算符优先级

C++ 引用难题 : My output appears reversed. 为什么?

linux - LD_LIBRARY_PATH 优先级