C – ‘printf’带前导零

我有一个浮点数,如4917.24。我想打印它总是在小数点前有五个字符,前面有零,小数点后面有三个数字。

我尝试printf(“?3f”,n)在我使用的嵌入式系统,但它打印*****。我有格式说明符正确吗?

您的格式说明符不正确。从我机器上的printf()手册页:

0 A zero ‘0‘ character indicating that zero-padding should be used rather than blank-padding. A ‘-‘ overrides a ‘0‘ if both are used;

Field Width:
An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, ‘.‘, followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

对于你的情况,你的格式将是.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

输出:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

请注意,此答案取决于嵌入式系统具有符合这些详细信息的printf()实现(许多嵌入式环境没有这样的实现)。

http://stackoverflow.com/questions/5007487/c-printf-with-leading-zeros

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:C – ‘printf’带前导零