【问题标题】:sprintf format warnings when compiling编译时的 sprintf 格式警告
【发布时间】:2023-03-15 12:22:01
【问题描述】:

变量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" 不应该代表浮动吗?
我怎样才能摆脱这个警告?

【问题讨论】:

  • 是您的编译器或 IDE 发出此警告吗?什么编译器/IDE 版本?
  • 它应该被隐式转换为双精度。但是 printf "%f" 期望 double
  • @Guille 它看起来像一个编译器错误。
  • @dbush 这些看起来像编译器消息,而不是 IDE。
  • 我们需要以下信息:您的平台、IDE、编译器和版本。

标签: c format printf


【解决方案1】:

为什么 %1.1f 期望双倍? “f”不应该代表浮动吗?我怎样才能摆脱这个警告?

"%1.1f" 期望 C 标准指定的 double
在 C 中,double 是 FP ... 参数和常量的默认浮点类型。

... 类型的 float 参数在传递之前转换为 doublesprintf(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); 也很可怕,因为缓冲区可能会被大的freq (如FLT_MAX)溢出。

控制宽度、大小并提供更多信息。导致缓冲区溢出或信息量不足的调试消息有什么用?

// 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 2019-11-23
    • 2022-06-21
    • 2011-05-09
    相关资源
    最近更新 更多