浮点常数

编程入门 行业动态 更新时间:2024-10-27 22:19:14
本文介绍了浮点常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于以下代码:

#include<stdio.h> int main() { float a = 0.7; printf("%.10f %.10f\n", 0.7f, a); return 0; }

我得到的输出是:

0.7000000000 0.6999999881

0.7000000000 0.6999999881

请解释为什么将a打印为0.6999999881而将文字常量打印为0.7000000000吗?

Please explain why a is printed as 0.6999999881 while the literal constant is printed as 0.7000000000 ?

在这种情况下,是否使用浮点常量取决于编译器?

Is the use of a floating point constant in this case compiler-dependent?

推荐答案

如果编译器将FLT_EVAL_METHOD定义为1或2,则为printf("%.10f",0.7f)打印的字符串获得"0.7000000000"是正常现象.

Obtaining "0.7000000000" as the string printed for printf("%.10f",0.7f) is normal behavior if the compiler defines FLT_EVAL_METHOD as 1 or 2.

实际上,在那种模式下,浮点常量可以精度为

Indeed, in that mode, floating-point constants can be represented at a precision beyond that of their type (C11 5.2.4.2.2:9):

除赋值和强制类型转换(这会删除所有额外的范围和精度)之外,使用浮点操作数的运算符产生的值以及需要进行常规算术转换的值和浮点常量的值将被评估为一种格式其范围和精度可能大于类型所要求的.

Except for assignment and cast (which remove all extra range and precision), the values yielded by operators with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type.

换句话说,对于下面的修改程序,打印0.7000000000 0.6999999881 FLT_EVAL_METHOD=2 是一种可能的行为.

In other words, printing 0.7000000000 0.6999999881 FLT_EVAL_METHOD=2 is one possible behavior for the modified program below.

#include<stdio.h> #include <float.h> int main() { float a=0.7; printf("%.10f %.10f FLT_EVAL_METHOD=%d\n",0.7f, a, (int)FLT_EVAL_METHOD); return 0; }

因为编译器将FLT_EVAL_METHOD定义为2,所以将printf("%.10f %.10f", 0.7f, 0.7)视为printf("%.10f %.10f", (double)0.7L, (double)0.7L).同样,printf("%.60Lf %.60Lf\n", (long double)0.7f, (long double)0.7)等同于printf("%.60Lf %.60Lf\n", 0.7L, 0.7L).

Because the compiler defines FLT_EVAL_METHOD to 2, printf("%.10f %.10f", 0.7f, 0.7) is treated as if it was printf("%.10f %.10f", (double)0.7L, (double)0.7L). Similarly, printf("%.60Lf %.60Lf\n", (long double)0.7f, (long double)0.7) is equivalent to printf("%.60Lf %.60Lf\n", 0.7L, 0.7L).

更多推荐

浮点常数

本文发布于:2023-08-01 08:58:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267056.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   常数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!