编写程序,求n! 编写程序,求1!+3!+5!+7!+9!。
时间: 2024-02-03 08:01:40 浏览: 95
以下是两种Java编写程序求阶乘的例子:
1. 求n!
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数n:");
int n = scanner.nextInt();
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println(n + "的阶乘是:" + factorial);
}
}
```
2. 求1!+3!+5!+7!+9!
```java
public class FactorialSum {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 9; i += 2) {
int factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
sum += factorial;
}
System.out.println("1!+3!+5!+7!+9!的和是:" + sum);
}
}
```
阅读全文