我正在编写一个非常小的代码,只有 scanf
和 printf
。我正在阅读一个双重值(value)并打印它。转换规范 %lf
可以正常读取 double 值。但是,它不适用于 printf。
当我尝试打印该值时,我得到的输出类似于 0.000000
double fag;
scanf("%lf", &fag);
printf("%lf", fag);
但是,如果我在 printf 中使用 %f 它会正常工作。
最佳答案
您使用的 C 标准库实现不符合 C99(或更新版本)。前言(第 5 段)中列出的更改包括:
%lf
conversion specifier allowed inprintf
l
长度修饰符的描述是(C99+TC3 7.19.6.1 par. 7,强调我的):
Specifies that a following
d
,i
,o
,u
,x
, orX
conversion specifier applies to along int
orunsigned long int
argument; that a followingn
conversion specifier applies to a pointer to along int argument
; that a followingc
conversion specifier applies to awint_t
argument; that a followings
conversion specifier applies to a pointer to awchar_t
argument; or has no effect on a followinga
,A
,e
,E
,f
,F
,g
, orG
conversion specifier.
%f
和 %lf
因此是等价的。两者都期望 double
因为参数匹配省略号(int printf(char const * restrict, ...);
中的 ...
)进行所谓的默认参数提升。其中,它们隐式地将 float
转换为 double
。这对 scanf()
无关紧要,因为指针不会被隐式转换。
因此,如果您不能或不想更新到较新的 C 标准库,%f
始终可以用在 printf()
格式字符串中以打印 float
或 double
。但是在 scanf()
格式字符串中,%f
需要 float*
而 %lf
需要 double*
.
关于c - 为什么转换规范 %lf 不适用于 printf 中的 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31600931/