使用变量设置浮点宽度和精度

时间:2018-02-03 05:42:31

标签: c printf width precision

我正在尝试使用用户可更改的宽度和精度打印浮点数。我遇到的问题是只读取精度字段,宽度被完全忽略。

int width = 4; int precision = 12;
printf("%*.*lf ", width , precision, value);

605.32364879299 5980.79287087619 802.32966093936
5839.78856776635 5355.77379680776 6602.20148319956

应该有一个空格填充,确保小数位排列,但好像宽度变量甚至没有被读取。

1 个答案:

答案 0 :(得分:1)

width is being completely ignored.

Certainly a mis-understanding of the field width. It is a minimum count of characters to print including the sign, digits, decimal point, etc.

An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces ... C11dr §7.21.6.1 4

int width = 4; int precision = 12;
double value =  605.32364879299;
printf("%*.*lf\n", width , precision, value);
width = 21;
printf("%*.*lf\n", width , precision, value);
/*
123456789012345678901 */

Output

605.323648792990       // Minimum width =  4, 16 characters in numeric text
     605.323648792990  // Minimum width = 21, 5 spaces + 16 characters in numeric text