C printf()格式:Float似乎不正确。

时间:2023-01-14 16:10:44

Something weird is happening when I try to format this output, it seems like the floats aren't right justified?

当我尝试格式化这个输出时,发生了一些奇怪的事情,看起来浮动效果不正确吗?

I want the decimal points to line up... Am I doing something wrong?

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

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

The output looks like this:

输出如下:

  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

Notice how the "Average I" and "Highest I" values aren't lining up? Shouldn't they be right justified by default? I expect the last displayed digit of the float would be to the right most position in the the 4 character space I have designated for the float. The longs are displaying the way I expected.

注意“平均I”和“最高I”值是如何排队的?它们不应该默认是正确的吗?我希望浮动的最后一个显示数字位于我为浮点数指定的4个字符空间中的最右边位置。多头展示了我的预期。

1 个解决方案

#1


2  

For your data, changing %4.1f to %5.1f will solve this problem. In a %m.nf format specifier, the m is the total width of the field in bytes, not the number of digits preceding the decimal point.

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

#1


2  

For your data, changing %4.1f to %5.1f will solve this problem. In a %m.nf format specifier, the m is the total width of the field in bytes, not the number of digits preceding the decimal point.

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