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

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

问题描述

什么是正确的格式说明符双击 printf中?它是%F 还是%LF ?我相信它的%F ,但我不知道。

code样品

 的#include<&stdio.h中GT;
诠释的main()
{
   双D = 1.4;
   的printf(%LF,D); //这是错的?
}


解决方案

%F是(或至少一个),纠正了双格式。有的一个浮法没有格式,因为如果你试图传递一个浮动的printf ,它会被提升到双击的printf 接收它 1 。 %LF也是目前的标准下可以接受的 - 在指定为如果遵循由˚F转换符(等等)。

请注意,这是一个地方,的printf 格式字符串从 scanf函数大为不同(和的fscanf 等)格式字符串。对于输出,你传递的的,将从浮动晋升为双击当作为可变参数参数传递。对于输入你传递一个的指针的,这是不松口,所以你必须要告诉 scanf函数是否要读浮动双击,所以 scanf函数 %F 意味着你要读浮动%LF 意味着你要阅读一个双击(并且,对于它的价值,为长双,使用% LF 对于任何一个的printf scanf函数)。


<子>
1. C99,§6.5.2.2/ 6:如果这表示调用的函数的前pression有一个类型不包括样机,整数促销活动是在每个参数执行,有float类型参数是提升一倍。这些被称为默认参数促销活动。在C ++中的措辞有所不同(例如,它用的是原型),但效果是一样的:所有的可变参数的参数进行默认促销他们由函数接收之前。

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.

Code sample

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

解决方案

"%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).

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: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it does use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.

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

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