c - 为什么转换规范 %lf 不适用于 printf 中的 Double

标签 c format-specifiers

我正在编写一个非常小的代码,只有 scanfprintf。我正在阅读一个双重值(value)并打印它。转换规范 %lf 可以正常读取 double 值。但是,它不适用于 printf。

当我尝试打印该值时,我得到的输出类似于 0.000000

double fag;
scanf("%lf", &fag);
printf("%lf", fag);

但是,如果我在 printf 中使用 %f 它会正常工作。

最佳答案

您使用的 C 标准库实现不符合 C99(或更新版本)。前言(第 5 段)中列出的更改包括:

%lf conversion specifier allowed in printf

l 长度修饰符的描述是(C99+TC3 7.19.6.1 par. 7,强调我的):

Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

%f%lf 因此是等价的。两者都期望 double 因为参数匹配省略号(int printf(char const * restrict, ...); 中的 ...)进行所谓的默认参数提升。其中,它们隐式地将 float 转换为 double。这对 scanf() 无关紧要,因为指针不会被隐式转换。

因此,如果您不能或不想更新到较新的 C 标准库,%f 始终可以用在 printf() 格式字符串中以打印 floatdouble。但是在 scanf() 格式字符串中,%f 需要 float*%lf 需要 double*.

关于c - 为什么转换规范 %lf 不适用于 printf 中的 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31600931/

相关文章:

c - 使用 GDB 在 "?? ()"中出现内存故障

c - 如何从 C 静态库中分离调试符号,然后将其加载到 GDB 中

c - scanf中使用[^符号的目的是什么?

c - char* 和 int* 之间的取消引用运算符 (*) 差异

c - 从文件中读取换行符分隔的项目

c - pthread : join a detached thread doesn't set errno correctly

c - %.#s 在 c 中的 printf 语句中的格式说明符

C 字符串。未获得所需的输出。我怎样才能输入这样的数字

c - 为什么在使用 printf 时在地址上使用表达式会表现得很奇怪

c++ - 如何解压缩已加载到 C 内存中的 zip 文件?