指定printf的可变小数位数

Cha*_*lie 1 c printf

我想知道如何使用scanf()允许用户键入他想要给出的答案的小数位数,以及如何将此变量输入到printf格式说明符中.例如

printf("The answer is %.(variable wanted here)f", answer);
Run Code Online (Sandbox Code Playgroud)

Jon*_*art 8

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

来自printf(3):

可以写"*"或"*m $"(对于某些十进​​制整数m)而不是十进制数字串来指定字段宽度分别在下一个参数或第m个参数中给出,这必须是属于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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

1.235
6.700
Stack Overflow
Run Code Online (Sandbox Code Playgroud)