C printf()格式:Float似乎没有正确的证明。

时间:2015-12-10 14:44:25

标签: c formatting printf

当我尝试格式化此输出时,会发生一些奇怪的事情,看起来浮动不是正确的吗?

我想要小数点排队......我做错了什么?

if (flushParams -> Volume > 0)
{   
    printf("\n      %-23s %7ld %2s  %7ld %3s  %2s %4.1f %1s  %9s %4.1f %2s %9s %4.1f %2s",
           "Intake Flush",
           event_data -> water1.ml, "ml",
           event_data -> water1.secs, "sec",
           "LB", event_data -> water1.bat, "V",
           "Average I", event_data -> water1.average_current, "mA",
           "Highest I", event_data -> water1.highest_current,  "mA");
    Message(event_data -> water1.message);
    printf("\n      %-11s = %02d", "Flush port", event_data -> portwater);
}
printf("\n\n      %-23s %7ld %2s  %7ld %3s  %2s %4.1f %1s  %9s %4.1f %2s %9s %4.1f %2s",
       "Sample",
       event_data -> sample.ml, "ml",
       event_data -> sample.secs, "sec",
       "LB", event_data -> sample.bat, "V",
       "Average I", event_data -> sample.average_current, "mA",
       "Highest I", event_data -> sample.highest_current,  "mA"); 
Message(event_data -> sample.message);
printf("\n      %-11s = %02d", "Sample port", event_data -> portsample);
printf("\n      ");
print_datetime(event_data -> time_off);
printf("  %3.1f Vbat  %3.1f %cC  PORT = %02d", 
       event_data -> vbat_off, event_data -> celcius_off, 248, event_data -> portend);

printf("\n");

输出如下:

  Intake Flush                101 ml       34 sec  LB 22.5 V  Average I 113.0 mA Highest I 118.0 mA Volume reached
  Flush port  = 00

  Sample                      320 ml      141 sec  LB 22.5 V  Average I 91.0 mA Highest I 97.0 mA Volume reached
  Sample port = 01
  12/09/15 17:11:14  22.6 Vbat  22.5 øC  PORT = 01

注意"平均I"和#34;最高的我"价值观不排队?默认情况下,他们不应该是正确的吗?我希望浮动的最后一个显示数字位于我为浮点数指定的4个字符空间中的最右边位置。多头展示了我的预期方式。

1 个答案:

答案 0 :(得分:2)

对于您的数据,将%4.1f更改为%5.1f将解决此问题。在%m.nf格式说明符中,m是字节的总宽度(以字节为单位),而不是小数点前面的位数。