'printf' 在 C 中带有前导零 [英] 'printf' with leading zeros in C
问题描述
我有一个浮点数,例如 4917.24
.我想把它打印成小数点前总是有五个字符,前导零,然后是小数点后三个数字.
I have a floating point number such as 4917.24
. I'd like to print it to always have five characters before the decimal point, with leading zeros, and then three digits after the decimal place.
我在我正在使用的嵌入式系统上尝试了 printf("%05.3f", n)
,但它打印了 *****
.我的格式说明符是否正确?
I tried printf("%05.3f", n)
on the embedded system I'm using, but it prints *****
. Do I have the format specifier correct?
推荐答案
您的格式说明符不正确.从我机器上的 printf()
手册页:
Your format specifier is incorrect. From the printf()
man page on my machine:
0
零0
"字符表示应使用零填充而不是空白 -填充.如果同时使用了-
",则会覆盖0
";
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);
精度:一个可选的句点,'.
',后跟一个可选的数字字符串,给出一个精度,指定出现在小数点后的位数,例如e 和 f 格式,或从字符串中打印的最大字符数;如果缺少数字字符串,则将精度视为零;
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;
对于您的情况,您的格式为 %09.3f
:
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f
", 4917.24);
return 0;
}
输出:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
请注意,此答案取决于您的嵌入式系统是否具有符合这些细节标准的 printf()
实现 - 许多嵌入式环境没有实施.
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
这篇关于'printf' 在 C 中带有前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!