浮点常数 [英] Floating point constant

查看:120
本文介绍了浮点常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码:

#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).

这篇关于浮点常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆