printf 格式说明符和 pow 函数中的 C float 或 double

标签 c printf double pow specifier

#include <stdio.h>
#include <math.h>

int main(void){

   printf("%lf\n", pow(1.0, 2.0));
   printf("%f\n", pow(1.0, 2.0));

   return 0;    
}

第一printf()给出输出 0.000000但第二个printf()给出输出 1.000000 。为什么?

在 Windows 7 64 位上使用 Codeblocks。

使用 gcc 命令进行编译,得到一个 .exe,两条语句都输出 1.000000。

如果我在 Codeblocks 上按 F9 进行编译,则第一个语句会得到 0.000000,第二个语句会得到 1.000000。

最后,如果我删除 #include <stdio.h>从 Codeblocks 中的源代码来看,全部给我 1.000000(没有警告或错误)。

最佳答案

您的代码应该在 C99 或 C11 编译器上为两行打印相同的值。 printf 的所有 float 参数始终转换为 double%lf%f 都做同样的事情(打印 double)。

在 C89 标准中,%lf 说明符是未定义的行为,并且 double 只能用 %f 打印。因此,也许您使用的是不支持 C99 标准的旧编译器。

有关 %lf 的标准相关部分:

C99,7.19.6.1/7:

l (ell) [...] has no effect on a following a, A, e, E, f, F, g,or G conversion specifier.

C89,4.9.6.1:

[...] an optional l (ell) specifying that a following d , i , o , u , x , or X conversion specifier applies to a long int or unsigned long int argument; an optional l specifying that a following n conversion specifier applies to a pointer to a long int argument; [...] If an h , l , or L appears with any other conversion specifier, the behavior is undefined.

关于printf 格式说明符和 pow 函数中的 C float 或 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927145/

相关文章:

c - 如何使用 C 中的 print 进行这样的输出

c - 在 C 中提取字符串模式(无库)

从 char* 数组中的条目创建新字符串

c - 以下 C 程序的输出应该是 3,但我得到 0,为什么?

c - 程序来计算c中的单词和字符的行数

C fprintf/fscanf 优化大文件速度

c - printf() - 打印错误的顺序。单独打印时有效

java - long/int 除法中的意外结果

c++ - 警告 C4244 : 'argument' : conversion from 'double' to 'float' , 可能丢失数据 - C++

floating-point - binary32 和 binary64 的有效十进制数字