printf中正确的格式说明符为double [英] Correct format specifier for double in printf

查看:212
本文介绍了printf中正确的格式说明符为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在printf中 double 的格式说明符是什么?是%f 还是%lf ?我相信它的%f 但我不确定。

What is the correct format specifier for double in printf? Is it %f or is it %lf? I believe its %f but I am not sure.

代码示例

#include <stdio.h>
int main()
{
   double d =1.4;
   printf("%lf", d); //is this wrong?
}


推荐答案

%f是双重格式(或至少一个)正确的格式。 printf ,将在 printf 之前升格为 double 收到它 1 %lf也符合现行标准 - l 被指定为无效果 f 转换说明符(等等)。

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

请注意,这是 printf 格式字符串与 scanf (和 fscanf 等)的格式字符串大不相同。对于输出,您传递一个,它将从 float 升级到 double 作为可变参数传递。对于输入,您传递的一个指针不会被提升,所以你必须告诉 scanf ,无论你想读一个 float double ,所以对于 scanf %f 表示您想阅读 float %lf 表示您想阅读一个 double (而且,对于一个 long double 而言,您使用% Lf printf scanf )。

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).


1. C99,§6.5.2.2/ 6:如果表示被调用函数的表达式的类型不包括一个原型,对每个参数执行整数促销,并且类型为float的参数被提升为双倍,这被称为默认参数促销。在C ++中,措辞有些不同(例如,它使用原型一词),但效果是相同的:所有可变参数在被函数接收之前都会进行默认升级。

这篇关于printf中正确的格式说明符为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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