用c++输出不同精度的PI
时间: 2024-05-05 16:17:33 浏览: 55
以下是使用C语言输出不同精度的PI的代码示例:
```
#include <stdio.h>
#include <math.h>
int main() {
double pi = M_PI;
printf("PI with 2 decimal places: %.2f\n", pi);
printf("PI with 4 decimal places: %.4f\n", pi);
printf("PI with 6 decimal places: %.6f\n", pi);
printf("PI with 8 decimal places: %.8f\n", pi);
printf("PI with 10 decimal places: %.10f\n", pi);
return 0;
}
```
这个程序使用了 `<math.h>` 中的 `M_PI` 常量,它是一个双精度浮点数,表示圆周率π的近似值。
输出结果如下:
```
PI with 2 decimal places: 3.14
PI with 4 decimal places: 3.1416
PI with 6 decimal places: 3.141593
PI with 8 decimal places: 3.14159265
PI with 10 decimal places: 3.1415926536
```
相关问题
c++输出不同精度的PI
由于圆周率PI是无限不循环小数,因此我们无法精确地输出它。以下是一些不同精度的PI输出:
- 3.14159(约等于)
- 3.14159265358979323846(常用的16位精度)
- 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679(常用的50位精度)
- 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679...(无限不循环小数)
用c++实现输出不同精度PI的功能(程序给出的PI值为 3.14159265358979323846)。具体要求如下: 输入的数为一个小于 15 的非负整数 n ; 输出 5 个不同精度的PI,即小数点后面分别保留 n,n+1 ,n+2 ,n+3 ,n+4 位的PI,每个PI分别独占一行。
以下是用 C 语言实现输出不同精度 PI 的代码:
#include <stdio.h>
int main() {
int n;
double pi = 3.14159265358979323846;
scanf("%d", &n);
printf("%.nf\n", pi); // n 位精度
printf("%.n1f\n", pi); // n+1 位精度
printf("%.n2f\n", pi); // n+2 位精度
printf("%.n3f\n", pi); // n+3 位精度
printf("%.n4f\n", pi); // n+4 位精度
return 0;
}
其中,%.nf 表示输出小数点后 n 位精度的浮点数,%.n1f 表示输出小数点后 n+1 位精度的浮点数,以此类推。输入的数为一个小于 15 的非负整数 n,可以通过 scanf 函数读入。