假设我有以下功能:
void fprint(float f, int ds) {
printf("%.%df\n", ds, f);
}
我希望调用者指定要打印的 float ,以及小数点后的位数。 (由 .%d
说明符指示)
但是,编译时我收到 2 个警告:
./sprint.h: In function ‘fprint’:
./sprint.h:19:14: warning: conversion lacks type at end of format [-Wformat=]
printf("%.%df\n", ds, f);
^
和
./sprint.h:19:12: warning: too many arguments for format [-Wformat-extra-args]
printf("%.%df\n", ds, f);
^~~~~~~~~
当调用它时:fprint(3.1422223f, 3);
,它会产生输出:%df
。
我还尝试交换函数声明中参数的顺序,但它会产生相同的警告。
我的问题是:如何将格式说明符(例如本例中的 %d
)注入(inject)现有格式说明符?
最佳答案
您可以在 printf
中使用星号来指定宽度或精度由参数给出——无需创建动态格式字符串。
printf("%.*f", ds, f);
手册页的 printf(3):
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.
, the precision is taken to be zero. A negative precision is taken as if the precision were omitted. This gives the minimum number of digits to appear ford
,i
,o
,u
,x
, andX
conversions, the number of digits to appear after the radix character fora
,A
,e
,E
,f
, andF
conversions, the maximum number of significant digits forg
andG
conversions, or the maximum number of characters to be printed from a string fors
andS
conversions.
关于c - printf 的参数用作格式说明符的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51140390/