利用面向对象方法求n!,并输出10!的值。用Java编写
时间: 2024-04-10 17:27:34 浏览: 28
以下是使用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
```
同样需要注意,这里使用了递归的方式计算阶乘,可能会在计算较大的数时导致栈溢出,因此需要根据具体需求进行优化。
面向对象方法求n!并输出10!的值
可以使用面向对象的方式来实现求阶乘的功能,下面是一个示例代码:
```python
class Factorial:
def __init__(self, n):
self.n = n
def calc(self):
if self.n == 0:
return 1
else:
return self.n * Factorial(self.n - 1).calc()
n = 10
f = Factorial(n)
print(f'{n}! = {f.calc()}')
```
输出结果:
```
10! = 3628800
```
注意,这里使用了递归的方式计算阶乘,可能会在计算较大的数时导致栈溢出,因此需要根据具体需求进行优化。