[英]sprintf format warnings when compiling
变量freq
声明如下:
void exciteFreqN(float freq, unsigned short N)
然后我使用以下指令:
sprintf(debugstr, "Cntr ticks:%d freq:%1.1f\r\n", ctphp, freq);
freq
的格式说明符"%1.1f"
显然是float
的(我认为)。
但是,编译器警告:
acquisitionXBEE.c: In function 'exciteFreqN':
***acquisitionXBEE.c:8519:5: warning: format '%1.1f' expects type 'double', but argument 4 has type 'float'
为什么"%1.1f"
期望double
? "f"
不应该代表浮动吗?
我怎样才能摆脱那个警告?
为什么 %1.1f 期望双倍? “f”不应该代表浮动吗? 我怎样才能摆脱那个警告?
"%1.1f"
需要 C 标准指定的double
精度值。
在 C 中, double
是 FP ...
arguments 和常量的默认浮点类型。
...
浮点类型的 arguments 在被传递之前被转换为double
float
。 sprintf(debugstr, "%1.1f %1.1f %1.1f ", 1.0, 2.0f, freq);
应该管用。
想想"%f"
暗示浮点的定点格式,而不是float
。
编译器有问题或只是以这种方式设计,因此不符合 C。
演员表可能会消除警告:
sprintf(debugstr, "Cntr ticks:%d freq:%1.1f\r\n", ctphp, (double) freq);
报告错误和/或转移到另一个编译器。
注意:如果不兼容的编译器在...
参数时故意不将float
提升为double
,则sprintf()
可能支持作为扩展的某些标志,例如"%$f"
以指示参数是float
。 检查您的编译器文档。 然后要小心制作这种实现特定的代码。
警告
即使在工作机器上sprintf(debugstr, "Cntr ticks:%d freq:%1.1f\r\n", ctphp, freq);
很可怕,因为缓冲区可能会FLT_MAX
类的大freq
而溢出。
控制宽度、大小并提供更多信息。 导致缓冲区溢出或信息量不大的调试消息有什么用?
// snprintf, v----size-----v %g
snprintf(debugstr, sizeof debugstr, "Cntr ticks:%d freq:%g\r\n", ctphp, freq);
// ... or pedantically to see all useful precision
snprintf(debugstr, sizeof debugstr, "Cntr ticks:%d freq:%.*g\r\n",
ctphp, FLT_DECIMAL_DIG, freq);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.