【发布时间】:2016-03-03 04:10:09
【问题描述】:
我正在用 Java 编写一个使用递归的简单代码。我想显示用户将输入的两个数字的乘积。我设法使用递归来做到这一点,但停留在我想证明产品可以写为(示例)10*5 = 5+5+5+5+5+5+5+5+5+ 5(10 次),或 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3(12 次)。到目前为止,这是我的代码。在代码中,我在应该写的地方添加了注释(示例)。谢谢。
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
【问题讨论】:
-
您在使用代码时遇到了具体问题吗?
-
问题是我不知道如何将产品分成更小的数字并将其展示给用户。正如我在示例中所说的(10 * 5 = 50)。现在,我想在屏幕上把那个产品写成 5+5+5+5+5+5+5+5+5+5
标签: java recursion multiplication