prod()方法在此Java程序中做什么? [英] What does the method prod() do in this Java program?
问题描述
public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
这是我受难的书中的一项练习.为什么程序不只是递归直到两个数字相等然后返回n
?另外,它说的是
This is an exercise in the book I am stumped on. Why would the program not just recurse until the two numbers are equal and then return n
? Also, where it says,
int result = n * recurse;
它如何将int n
乘以递归,即(int, int)
?如何将一个整数乘以两个整数?
How does it multiply int n
by recurse which would be (int, int)
? How can it multiply one integer by a set of two integers?
我以什么方式误解了该程序?
In what way am I misunderstanding this program?
这是一个不同的问题,因为我没有使用阶乘
This is a different question because I am not using factorials
推荐答案
prod(x,y)
在x=1
时等效于y!
.
如果x
与1
不同,则对其进行递归乘法(y * (y- 1) * (y -2) .... )
直到y = x
.
假设y > x
.
prod(x,y)
is equivalent to y!
when x=1
.
If x
is different from 1
, then its doing recursive multiplication (y * (y- 1) * (y -2) .... )
until y = x
.
Assuming y > x
.
顺便说一句,如果x > y
然后prod()
将会崩溃.
By the way, if x > y
then prod()
will crash.
这篇关于prod()方法在此Java程序中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!