使用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,anint
argument supplies the field width or precision. The arguments specifying field width,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.