在Java中计算某个整数的阶乘,如n!=n*(n-1)(n-2).....4321,n的值从控制台录入。,使用循环
时间: 2023-05-23 08:03:18 浏览: 57
可以使用for循环实现计算整数n的阶乘,代码如下:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int factorial = 1;
for (int i = n; i > 0; i--) {
factorial *= i;
}
System.out.println(n + "! = " + factorial);
}
}
```
例如,如果在控制台上输入5,则输出结果为:5! = 120
相关问题
在Java中计算某个整数的阶乘,如n!=n*(n-1)*(n-2).....4*3*2*1,n的值从控制台录入。
可以使用递归或循环,以下是使用递归的 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 result = factorial(n);
System.out.println(n + "的阶乘是:" + result);
}
public static int factorial(int n) {
if (n == 1 || n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
1. 编写线程程序,在新线程中完成计算某个整数的阶乘。分别用Thread类和Runnable接口实现。
使用Thread类实现:
```java
public class FactorialThread extends Thread {
private int n;
public FactorialThread(int n) {
this.n = n;
}
@Override
public void run() {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
使用Runnable接口实现:
```java
public class FactorialRunnable implements Runnable {
private int n;
public FactorialRunnable(int n) {
this.n = n;
}
@Override
public void run() {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
使用方法:
```java
public class Main {
public static void main(String[] args) {
// 使用Thread类实现
Thread t1 = new FactorialThread(5);
t1.start();
// 使用Runnable接口实现
FactorialRunnable r = new FactorialRunnable(6);
Thread t2 = new Thread(r);
t2.start();
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)