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

查看:60
本文介绍了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 it's %f, but I am not sure.

#include <stdio.h>

int main()
{
   double d = 1.4;
   printf("%lf", d); // Is this wrong?
}

推荐答案

"%f" 是(或至少一种)双精度型的正确格式.没有 float 的格式,因为如果您尝试将 float 传递给 printf,它会在printf收到1之前被提升为double."%lf" 在当前标准下也是可以接受的——如果后跟 f 转换说明符,l 被指定为无效等等).

"%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 等)格式字符串有很大不同的地方.对于输出,您要传递一个 value,当作为可变参数传递时,该值将从 float 提升为 double.对于输入,您传递的是一个指针,该指针不会被提升,因此您必须告诉 scanf 是否要读取 floatdouble,所以对于scanf%f 意味着你要读取一个float%lf 表示您想要读取 double(并且,对于 long double,您可以使用 %Lfprintfscanf).

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 类型的参数提升为 double.这些被称为默认参数提升."在 C++ 中,措辞有些不同(例如,它不使用原型"一词),但效果是相同的:所有可变参数在被函数接收之前都会经过默认提升.

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

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