[英]Java multiplication using Recursion
我正在使用递归的Java语言编写一个简单的代码。 我想显示用户将输入的两个数字的乘积。 我设法使用递归做到了这一点,但停留在我想证明该产品可以写为(例如)10 * 5 = 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));
}
}
}
}
StringBuilder应该被视为
StringBuilder buf = new StringBuilder (a);
将此StringBuilder参数传递给multiRec
然后将multiRec更改为
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
然后,完成后只需打印其值
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.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// 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 {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.