编写程序,求n!。 编写程序,求1!+3!+5!+7!+9!。
时间: 2023-12-01 09:42:39 浏览: 62
以下是两种Java求阶乘的例子:
1. 普通方法
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
int fac = 1;
for (int i = 1; i <= n; i++) {
fac *= i;
sum += fac;
}
System.out.println(sum);
}
}
```
2. 递归方法
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); int n = sc.nextInt();
int sum = 0;
for (int i = 1; i <= n; i += 2) {
sum += factorial(i);
}
System.out.println(sum);
}
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
```
以下是Java求1!+3!+5!+7!+9!的例子:
```java
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 9; i += 2) {
sum += factorial(i);
}
System.out.println(sum);
}
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
```
阅读全文