C是否舍入浮点常数

A question about floating-point precision in Go让我想知道C如何处理这个问题.

使用C中的以下代码

float a = 0.1;

是否具有最接近的IEEE 754二进制表示:

00111101110011001100110011001101 (Decimal:  0.10000000149011612)

或者只是将它裁剪成:

00111101110011001100110011001100 (Decimal:  0.09999999403953552)

或者根据编译器/平台的不同而不同?

解决方法

允许实现(或者甚至多一个):

For decimal floating constants,and also for hexadecimal floating constants when FLT_RADIX is not a power of 2,the result is either the nearest representable value,or the larger or smaller representable value immediately adjacent to the nearest representable value,chosen in an implementation-defined manner.

(C11,§6.4.4.2/ 3)

从C99开始,我们已经有了十六进制浮点常量,因此您可以精确指定所需的位(假设实现提供了二进制浮点:)),所以您可以说,例如:

float a = 0x1.99999Ap-4;

对于IEEE 754 32位浮点数:

#include <stdio.h>
int main() {
  float a = 0.1;
  float low  = 0x0.1999999p0;
  float best = 0x0.199999ap0;
  float high = 0x0.199999bp0;
  printf("a is %.6a or %.16f,which is either %.16f,%.16f or %.16f\n",a,low,best,high);
  return 0;
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...