用c语言中的do-while语句如何计算1+1/2+1/3+……+1/n.
时间: 2023-05-19 11:06:51 浏览: 747
可以使用以下代码来计算1 1/2 1/3 …… 1/n:
```
#include <stdio.h>
int main() {
int n;
float sum = 0.0;
printf("请输入一个正整数n:");
scanf("%d", &n);
int i = 1;
do {
sum += 1.0 / i;
i++;
} while (i <= n);
printf("1 + 1/2 + 1/3 + ... + 1/%d = %f", n, sum);
return 0;
}
```
这个程序会先让用户输入一个正整数n,然后使用do-while循环来计算1 1/2 1/3 …… 1/n的和,并将结果输出。
相关问题
用C语言do-while语句编写1+1/2+1/3+...+.1/n的值,要求n用键盘输入
以下是使用C语言do-while语句编写1+1/2+1/3+...+1/n的值的程序,其中n由键盘输入:
```c
#include <stdio.h>
int main() {
int n, i = 1;
float s = 0;
printf("请输入n的值:");
scanf("%d", &n);
do {
s += 1.0 / i;
i++;
} while (i <= n);
printf("1+1/2+1/3+...+1/n的值为:%f\n", s);
return 0;
}
```
在C语言中用do-while语句计算e≈1+1/1!+1/2!+…+1/n!
以下是在C语言中使用do-while语句计算e≈1+1/1!+1/2!+…+1/n!的代码:
```c
#include <stdio.h>
int main() {
int n, i = 1;
double s = 1, f = 1;
printf("请输入一个正整数(赋给n):");
scanf("%d", &n);
do {
f *= i; // 计算i的阶乘
s += 1.0 / f; // 计算每一项的值并加到s中
i++; // i加1
} while (i <= n);
printf("e ≈ %f\n", s); // 输出结果
return 0;
}
```
该程序中,我们使用了do-while语句来计算e的近似值。在循环中,我们定义了变量i表示当前项的下标,变量s表示e的近似值,变量f表示当前项的分母的阶乘。在每次循环中,我们先计算当前项的分母的阶乘,然后计算当前项的值,并将其加到s中。最后输出s的值即可。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)