问题描述
对于以下代码:
#include<stdio.h>
int main()
{
float a = 0.7;
printf("%.10f %.10f\n", 0.7f, a);
return 0;
}
我得到的输出是:
请解释为什么将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):
换句话说,对于下面的修改程序,打印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)
.
这篇关于浮点常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!