用JAVA写一个程序:利用面向对象方法求n!,并输出10!的值
时间: 2024-05-21 14:13:05 浏览: 16
public class Factorial {
public static void main(String[] args) {
int n = 10;
long result = factorial(n);
System.out.println(n + "! = " + result);
}
public static long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
输出结果:
10! = 3628800
相关问题
利用面向对象方法求n!,并输出10!的值。用Java编写
以下是使用Java编写的面向对象方法来计算阶并输出10!的值示例代码:
```
public class Factorial {
public int calculateFactorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int n = 10;
Factorial factorial = new Factorial();
int result = factorial.calculateFactorial(n);
System.out.println(n + "! = " + result);
}
}
```
在这个示例中,我们创建了一个名为Factorial的类,其中包含一个名为calculateFactorial的方法来计算阶乘。在该方法内部,我们使用循环来递增乘数并累积结果。在主方法中,我们实例化Factorial类,调用calculateFactorial方法来计算10!的值,并将结果打印输出。
运行这段代码,你将得到输出结果:
```
10! = 3628800
```
这是10的阶乘结果。
java实现面向对象方法求n!并输出10!的值
当然,也可以使用Java语言来实现求阶乘的功能,下面是一个示例代码:
```java
public class Factorial {
private int n;
public Factorial(int n) {
this.n = n;
}
public int calc() {
if (n == 0) {
return 1;
} else {
return n * new Factorial(n - 1).calc();
}
}
public static void main(String[] args) {
int n = 10;
Factorial f = new Factorial(n);
System.out.printf("%d! = %d", n, f.calc());
}
}
```
输出结果:
```
10! = 3628800
```
同样需要注意,这里使用了递归的方式计算阶乘,可能会在计算较大的数时导致栈溢出,因此需要根据具体需求进行优化。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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)