c - 如何控制 double 变量小数点字符后出现的位数?

标签 c printf double format-specifiers

我想在打印数据类型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, 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

关于c - 如何控制 double 变量小数点字符后出现的位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37720657/

相关文章:

当端口关闭时,使用套接字检查远程服务器上的开放端口会挂起,C

c - 使用宏扩展从 C 函数返回 double

hex - printf byte to hex string 奇怪的输出

iphone - double 中的 objective-c stringvalue

android - 如何在android中使用带双参数的AsyncTask

c - 如何调用传递给另一个函数的任意 C 函数?

c++ - 通过c++程序调用c(编译文件)

c - 最快使用超过 64 字节的数据集?

c - 为什么 "fputc "在这里不起作用?它正在抛出垃圾字母

c - C 中 printf 的不逻辑总线错误