分别用while语句计算e≈1+1/1!+1/2!+...+1/n!
时间: 2024-01-29 12:02:17 浏览: 71
以下是两种使用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!的Python代码:
```python
import math
n = 0
e = 0
item = 1
while True:
e += item
n += 1
item = item / n
if item < 1e-6:
break
print("e ≈", 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);
}
}
```
阅读全文