printf 在变量中传递的具有精度(小数位数)的浮点值

printf a float value with precision (number of decimal digits) passed in a variable

我可以使用

打印精度为 3 位小数的浮点值
double f = 1.23456;
printf( "%.3f", f );

现在我有请求的小数位数,它不是固定的,而是存储在一个变量中

int precision;
precision = atoi( argv[ 1 ] ); // ...just for example
double f = 1.23456;

如何使用 precision 中指定的小数位数打印 f 的值?

我可以通过编程方式为 printf 编写格式字符串,但我想知道是否有更简单的方法来做到这一点。

使用".*"

printf("%.*f", precision, f);

示例:

>>> printf("%.*f", 5, 3.14)
"3.14000"

精度

这叫做精度字段。 根据 man pages,

The precision: An optional precision, in the form of a period ('.') followed by an optional decimal digit string. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just '.', or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

宽度

宽度字段类似,适用于更多格式,例如 "%*s"。只需删除 .。 它将根据需要用空格或零填充输出。 如果 precision 为负数,则字符串将左对齐。

>>> printf("%*s\n", 10, "left?")
"     left?"
>>> printf("%*s\n", -10, "left?")
"left?     "

根据 man pages,

The field width: An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. A negative field width is taken as a '-' flag followed by a positive field width. In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.