用C语言编写s=1+(1+2)+...+(1+2...+n)
时间: 2023-09-09 15:06:00 浏览: 72
以下是用C语言编写的代码:
```
#include <stdio.h>
int main() {
int n, s = 0;
printf("请输入 n:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
s += i * (i + 1) / 2;
}
printf("s = %d\n", s);
return 0;
}
```
输入n后,使用for循环计算每个括号内的和,并将它们累加到s中。在每个括号中,使用等差数列求和公式:$1+2+...+n=\frac{n(n+1)}{2}$,计算括号内的和。最后输出s的值。
相关问题
用C语言编写s=1+1/2!+1/3!+...+1/n! n由键盘给出
```c
#include <stdio.h>
int main() {
int n;
printf("请输入n的值:");
scanf("%d", &n);
double s = 1; // 初始化s为1
int i, j;
for (i = 2; i <= n; i++) { // i从2到n循环
double f = 1; // 计算i的阶乘
for (j = 1; j <= i; j++) {
f *= j;
}
s += 1 / f; // 加上1/i!的值
}
printf("s = %f\n", s);
return 0;
}
```
C语言编写s=1+1/1!+1/2!+1/3!+...+1/N!
```c
#include <stdio.h>
int main() {
int i, n;
double s = 1, factorial = 1; // 使用 double 类型存储结果和阶乘
printf("请输入 N:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
factorial *= i;
s += 1.0 / factorial; // 注意使用 1.0 而不是 1,确保结果为浮点数
}
printf("s = %.10f", s);
return 0;
}
```
输出:
```
请输入 N:10
s = 2.7182818011
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)