printf浮点数的可变小数位数
我找到了有趣的格式来打印非终止的固定长度字符串,如下所示:
char newstr[40] = {0}; sprintf(newstr,"%.*s", sizeof(mystr), mystr);
所以我想也许在printf命令下有一种打印浮点数的方法……
“%8.2f”
能够选择整数的小数位数。
像这样的东西:
sprintf(mystr, "%d %f", numberofdecimals, floatnumbervalue)
编辑 – 解决方案:
(用于将浮点数舍入和清除到所需精度)。
int precision = 2; char kolf[16] = {0}; sprintf(kolf, "%8.*f", precision, mystruct.myfloat); float kol = atof(kolf);
您还可以使用带浮点的".*"
,另请参阅http://www.cplusplus.com/reference/cstdio/printf/ (指C ++,但格式说明符类似)
.number :对于a,A,e,E,f和F说明符:这是小数点后要打印的位数(默认情况下,这是6)。
…
。* :格式字符串中未指定精度,但作为必须格式化的参数之前的附加整数值参数。
例如:
float floatnumbervalue = 42.3456; int numberofdecimals = 2; printf("%.*f", numberofdecimals, floatnumbervalue);
输出:
42.35
对于字段宽度和精度,您也可以使用星号:
printf("%*.*f\n", myFieldWidth, myPrecision, myFloatValue);
参见例如此参考文献 。