c语言3.+编写程序计算下列S的值。 (1)+S=1-1/2+1/3-1/4+1/5+……-1/100 (2)+S=1!+2!+3!+……10! (3)+S=1/2+2/3+3/5+5/8+……++(
时间: 2023-11-20 18:06:19 浏览: 233
以下是三个C语言程序,分别计算了三个不同的数学公式的值:
1.计算1-1/2+1/3-1/4+1/5+……-1/100的值
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 100;
double sum = 0;
int flag = 1;
for (int i = 1; i <= n; i++)
{
sum += flag * 1.0 / i;
flag = -flag;
}
printf("%.4lf", sum);
return 0;
}
```
2.计算1!+2!+3!+……10!的值
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 10;
int sum = 0;
int fac = 1;
for (int i = 1; i <= n; i++)
{
fac *= i;
sum += fac;
}
printf("%d", sum);
return 0;
}
```
3.计算1/2+2/3+3/5+5/8+……的值
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 20;
double sum = 0;
int a = 1, b = 2;
for (int i = 1; i <= n; i++)
{
sum += (double)a / b;
int temp = b;
b = a + b;
a = temp;
}
printf("%.4lf", sum);
return 0;
}
```
阅读全文