我想在打印数据类型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章,
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
, andF
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
。
关于c - 如何控制 double 变量小数点字符后出现的位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37720657/