利用do...while语句计1+1/2+1/3+...+1/n。
时间: 2023-11-11 07:02:58 浏览: 124
以下是利用do...while语句计算1+1/2+1/3+...+1/n的代码:
```
int n = 10;
double sum = 0.0;
int i = 1;
do {
sum += 1.0 / i;
i++;
} while (i <= n);
printf("sum = %f", sum);
```
输出结果为:sum = 2.928968
相关问题
分别用while语句、do-while语句、for语句编写程序,计算e≈1+1/1!+1/2!+...+1/n!
使用while语句计算e≈1+1/1!+1/2!+...+1/n!的代码如下所示:
```java
int n = 20;
double sum = 1.0, number = 1.0;
int i = 1;
while (i <= n) {
number /= i;
sum += number;
i++;
}
System.out.println("使用while循环计算的e≈" + sum);
```
使用do-while语句计算e≈1+1/1!+1/2!+...+1/n!的代码如下所示:
```java
int n = 20;
double sum = 1.0, number = 1.0;
int i = 1;
do {
number /= i;
sum += number;
i++;
} while (i <= n);
System.out.println("使用do-while循环计算的e≈" + sum);
```
使用for语句计算e≈1+1/1!+1/2!+...+1/n!的代码如下所示:
```java
int n = 20;
double sum = 1.0, number = 1.0;
for (int i = 1; i <= n; i++) {
number /= i;
sum += number;
}
System.out.println("使用for循环计算的e≈" + sum);
```
阅读全文