C语言 在 C 中带有前导零的 printf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5007487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:48:34  来源:igfitidea点击:

printf with leading zeros in C

cformattingprintf

提问by fred basset

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, then three digits after the decimal place.

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

I tried printf("%05.3f", n)on the embedded system I'm using, but it prints *****. Do I have the format specifier correct?

我尝试printf("%05.3f", n)了我正在使用的嵌入式系统,但它打印*****. 我的格式说明符是否正确?

回答by Carl Norum

Your format specifier is incorrect. From the printf()man page on my machine:

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

0A 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 eand fformats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

0零 ' 0' 字符指示应使用零填充而不是空白填充。如果两者都使用,则“ -”覆盖“ 0”;

字段宽度:指定字段宽度的可选数字字符串;如果输出字符串的字符少于字段宽度,它将在左侧(或右侧,如果已给出左调整指示符)填充空白以构成字段宽度(注意前导零是一个标志,但嵌入的零是字段宽度的一部分);

精度:一个可选的句点 ' .',后跟一个可选的数字字符串,给出一个精度,用于指定小数点后出现的位数,对于ef格式,或从字符串中打印的最大字符数;如果缺少数字字符串,则精度被视为零;

For your case, your format would be %09.3f:

对于您的情况,您的格式将是%09.3f

#include <stdio.h>

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

Output:

输出:

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

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 nothave such an implementation.

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