提问人:dargaud 提问时间:9/26/2023 最后编辑:Jabberwockydargaud 更新时间:9/30/2023 访问量:120
使用 %f 但获取“format %f expects type double”
Using %f but get "format %f expects type double"
问:
除非我累了,否则我不明白以下警告。我不确定编译器基于什么(它是使用 Microchip 的 XC16 作为 dsPIC33 微控制器的 MPLAB X 6)。
float test=5.5;
printf("%f\n", test);
warning: format '%f' expects type 'double', but argument 2 has type 'float'
通常用于浮点和双精度,对吧? 不存在,所以我怎么能让这个警告消失而不做%f
%lf
%hf
printf("%f\n", (double)test)
答:
这是一个编译器错误。MPLAB 编译器因其非常差的 C 标准合规性而臭名昭著。在Microchip论坛上,有很多非常古老的帖子报告了同样的问题(示例)。
正如注释中所指出的,是一个可变参数函数,传递给它的所有参数都受制于称为“默认参数升级”的东西,在这种情况下,这意味着传递的参数在传递给 时总是会隐式提升到。printf
float
double
printf
因此,由于这些强制性的默认参数提升,无论你尝试什么,你都无法通过。由于这个原因,C 标准甚至没有提到,例如 C17 7.21.6.1 §8:float
float
f,F
一个论点......double
与您的问题无关,您已经混合了,这里:.常量的类型为 - 给出一个 .float
double
float test=5.5;
5.5
double
5.5f
float
你应该养成一种习惯,不要在同一个表达式中混合 或整数操作数,因为 C 语言有各种微妙的隐式提升规则。float
double
评论
printf
%lf
printf
Normally is for and for , right ?
%f
float
%lf
double
No.
With and friends, and are both for .printf()
"%f"
"%lf"
double
"l (ell) ... has no effect on a following a, A, e, E, f, F, g, or G conversion specifier."
C Spec: The fprintf function
float
arguments to a function like are first converted to a and it is a that receives....
int printf(const char * restrict format, ...);
double
double
printf()
With and friends, matches a and matches a .scanf()
"%f"
float *
"%lf"
double *
how can I make this warning go away without doing
printf("%f\n", (double)test)
The warning does not follow the C spec. See if that particular warning can be disabled.
Use a compliant compiler.
Of course one could change code: make a , don't use , ...
test
double
printf()
评论
printf
double
double
printf
%f
%lf
test
double
test
double
%f
double
float
double
float
float
printf()
float
double