用C语言写出求π或e^1/2的程序
时间: 2024-02-23 07:00:11 浏览: 76
C语言蒙特卡罗算法估算π值源程序.zip
以下是用C语言实现近似计算π的程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n = 1000000;
int m = 0;
double x, y;
srand(time(NULL));
for (int i = 0; i < n; i++) {
x = (double)rand() / RAND_MAX * 2 - 1;
y = (double)rand() / RAND_MAX * 2 - 1;
if (x * x + y * y <= 1) {
m++;
}
}
double pi = 4.0 * m / n;
printf("Pi is approximately %.6f\n", pi);
return 0;
}
```
以下是用C语言实现计算e^1/2的程序:
```
#include <stdio.h>
#include <math.h>
int main() {
int n = 10;
double x = 0.5;
double e = 0;
for (int i = 0; i < n; i++) {
e += pow(x, i) / tgamma(i + 1);
}
printf("e^1/2 is approximately %.6f\n", e);
return 0;
}
```
其中,tgamma()是计算阶乘的函数,需要#include <math.h>头文件。
阅读全文