如何控制双精度变量小数点后的位数?

How to control the number of digits to appear after the decimal-point character for a double variable?

我想在打印数据类型 double 的数字时打印小数点后的 n 位数。但是,必须使用 scanf().

从用户处获取整数 n
double pi = acos(-1);
int n;
printf("\nEnter the number of decimal digits required : ");
scanf("%d",&n);

现在,如何使用printf()打印圆周率的n位数?

引用 C11,章节 §7.21.6.1/p4,用于 precision 选项,

Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

  • An optional precision that gives [...] the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, [...] The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; [...]

并且在第 5 段中,

As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. [...]

因此,您可以使用格式

printf("%.*f", precision, variable);

喜欢

printf("%.*f", n, pi);

使用取自用户的精度n