#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/