java求1!+2!+...+N!
时间: 2023-12-30 10:07:00 浏览: 46
以下是Java求1!+2!+...+N!的例子:
```java
public static int jc(int x) {
int ret=1;
int i=0;
for(i=1;i<=x;i++) {
ret=ret*i;
}
return ret;
}
public static int sum(int n) {
int i=0;
int j=1;
int sum=0;
for(i=1;i<=n;i++) {
j=jc(i);
sum+=j;
}
return sum;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
int sum=sum(n);
System.out.println(sum);
}
```
相关问题
Java求1! + 2! + ... + n!的和
要求求1! 2! ... n!的和,可以按照以下步骤编写Java代码:
1. 导入Scanner类
2. 创建主类和主方法
3. 创建Scanner对象sc以接收用户输入
4. 通过sc.nextInt()方法获取用户输入的n的值
5. 创建变量sum并初始化为0
6. 使用for循环计算1! 2! ... n!的和,每次迭代都将阶乘结果加到sum中
7. 打印出最终的结果sum
8. 关闭Scanner对象sc
Java代码如下所示:
```java
import java.util.Scanner;
public class Test19 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i;
int sum = 0;
int result = 0;
for (i = 1; i <= n; i++) {
int factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
sum += factorial;
}
System.out.println(sum);
sc.close();
}
}
```
java中求1!+2!+...+N!
以下是Java中求1!+2!+...+N!的代码示例:
```java
public class FactorialSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
int factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
sum += factorial;
}
System.out.println(sum);
}
}
```
该程序首先使用Scanner类获取用户输入的整数n,然后使用两个for循环计算1!+2!+...+N!的和,其中外层循环控制计算的次数,内层循环计算每个数的阶乘。最后将每个数的阶乘相加得到结果并输出。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)