为 printf 指定可变的小数位数

Specify variable number of decimal places to printf

我想知道如何使用 scanf() 让用户输入他想要的答案的小数位数,以及如何将此变量输入 printf 格式说明符。例如

printf("The answer is %.(variable wanted here)f", answer);

如果您使用 * 作为您的字段精度说明符,它告诉 printf 它是可变的。然后,您指定一个额外的前置 int 参数来告诉 printf 所需的精度。

来自printf(3)

Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int.

请注意,这也适用于设置从字符串打印的最大字符数。

#include <stdio.h>

int main(void)
{
    int places = 3;
    printf("%0.*f\n", places, 1.23456789);
    printf("%0.*f\n", places, 6.7);

    char buf[] = "Stack OverflowXXXXXXXX";
    printf("%.*s\n", 14, buf);

    return 0;
}

输出:

1.235
6.700
Stack Overflow