使用 sprintf 动态设置精度
Set precision dynamically using sprintf
使用 sprintf 和通用语法 "%A.B"
我可以这样做:
double a = 0.0000005l;
char myNumber[50];
sprintf(myNumber,"%.2lf",a);
我可以在格式字符串中动态设置 A 和 B 吗?
是的,你可以做到。您需要使用星号 *
作为字段宽度,使用 .*
作为精度。然后,您需要提供带有值的参数。像
sprintf(myNumber,"%*.*lf",A,B,a);
注意:A
和B
需要输入int
。来自 C11
标准,第 §7.21.6.1 章,fprintf()
函数
... a field width, or precision, or both, may be indicated by an asterisk. In
this case, an int
argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a -
flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.
是 - 您使用“*”,例如
sprintf(mynumber, "%.*lf", 2, a);
使用 sprintf 和通用语法 "%A.B"
我可以这样做:
double a = 0.0000005l;
char myNumber[50];
sprintf(myNumber,"%.2lf",a);
我可以在格式字符串中动态设置 A 和 B 吗?
是的,你可以做到。您需要使用星号 *
作为字段宽度,使用 .*
作为精度。然后,您需要提供带有值的参数。像
sprintf(myNumber,"%*.*lf",A,B,a);
注意:A
和B
需要输入int
。来自 C11
标准,第 §7.21.6.1 章,fprintf()
函数
... a field width, or precision, or both, may be indicated by an asterisk. In this case, an
int
argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a-
flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.
是 - 您使用“*”,例如
sprintf(mynumber, "%.*lf", 2, a);