在C中带有前导零的printf [英] printf with leading zeros in C

查看:265
本文介绍了在C中带有前导零的printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点数,例如 4917.24 。我想打印它始终有小数点前五个字符,前导零,然后三位小数点后。



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

解决方案

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


0 表示零填充应该是零的 0 使用而不是空白填充。如果 - ,则会覆盖 0 两者都被使用;

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

精度:一个可选的期间' ,然后是一个可选的数字字符串,用于指定小数点后面出现的位数, e f 格式从字符串打印的最大字符数;如果数字字符串丢失,精度被视为零;

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

  #include< stdio.h> 
$ b $ int main(int argc,char ** argv)
{
printf(%09.3f\,4917.24);
返回0;



$ b $ p $输出:

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

请注意,这个答案的条件是嵌入式系统有一个符合标准的 printf()对于这些细节 - 许多嵌入式环境没有这样的实现。


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.

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

解决方案

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

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;

For your case, your format would be %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 not have such an implementation.

这篇关于在C中带有前导零的printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆