用java写编写应用程序求1!+2!+..+10! ●同上,修改为可以输入终止值(练习输入语法)
时间: 2024-02-13 11:59:59 浏览: 79
java代码-使用java解决1!+2!+……+N!的源代码
5星 · 资源好评率100%
好的,以下是Java代码实现:
求1!+2!+..+10!:
```java
public class Main {
public static void main(String[] args) {
int n = 10;
int factorial = 1;
int sum = 0;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
System.out.println("1!+2!+..+10! = " + sum);
}
}
```
输入终止值:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入终止值: ");
int n = sc.nextInt();
int factorial = 1;
int sum = 0;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
System.out.println("1!+2!+..+" + n + "! = " + sum);
}
}
```
和上一题类似,只需要在循环中累加阶乘的和即可。
阅读全文