分别用while语句计算e≈1+1/1!+1/2!+...+1/n!
时间: 2024-01-29 21:02:17 浏览: 82
以下是两种使用while语句计算e的方法:
方法一:
```java
public class Main {
public static void main(String[] args) {
int n = 0;
double e = 1.0;
double item = 1.0;
while (item >= 1e-6) {
n++;
item /= n;
e += item;
}
System.out.println(e);
}
}
```
方法二:
```java
public class Main {
public static void main(String[] args) {
int n = 0;
double e = 1.0;
double item = 1.0;
while (n < 10) {
n++;
item *= n;
e += 1.0 / item;
}
System.out.println(e);
}
}
```
相关问题
用while语句计算e≈1+1/1!+1/2!+…+1/n!
以下是使用while语句计算e≈1+1/1!+1/2!+…+1/n!的代码:
```java
public class Main {
public static void main(String[] args) {
int n = 10;
double e = 1.0;
int i = 1;
int factorial = 1;
while (i <= n) {
factorial *= i;
e += 1.0 / factorial;
i++;
}
System.out.println("e ≈ " + e);
}
}
```
、分别用+while+语句、do-while+语句、for+语句编写程序,计算+e≈1+1/1!+1/2!+...+1/n!
以下是三种不同的语句实现计算e的程序:
1. while语句实现
```java
int n = 1;
double sum = 1, item = 1;
while (true) {
item = item / n;
sum += item;
n++;
if (item < 1e-6) {
break;
}
}
System.out.println("使用while循环计算的e=" + sum);
```
2. do-while语句实现
```java
int n = 1;
double sum = 1, item = 1;
do {
item = item / n;
sum += item;
n++;
} while (item >= 1e-6);
System.out.println("使用do-while循环计算的e=" + sum);
```
3. for语句实现
```java
int n = 1;
double sum = 1, item = 1;
for (int i = 1; item >= 1e-6; i++) {
item = item / i; sum += item;
n = i;
}
System.out.println("使用for循环计算的e=" + sum);
```
阅读全文