微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
}

原文地址:https://www.jb51.cc/c/118634.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐