C是否舍入浮点常数

C是否舍入浮点常数,第1张

概述A question about floating-point precision in Go让我想知道C如何处理这个问题. 使用C中的以下代码: float a = 0.1; 是否具有最接近的IEEE 754二进制表示: 00111101110011001100110011001101 (Decimal: 0.10000000149011612) 或者只是将它裁剪成: 001111011100 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是否舍入浮点常数全部内容,希望文章能够帮你解决C是否舍入浮点常数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1240043.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存