我希望输出类似于"6 + 6 + 6 + 6 = 24"
,但是看到System.out.print(x + " + ")
在递归循环中,它最终输出:"6 + 6 + 6 + 6 + = 24"
在主程序中,我有单独的一行代码来输出结果: System.out.print(“ =” +结果);
public static int recursiveMultiply(int x, int y){
//Make y positive
if(y < 0)
return recursiveMultiply(-x, -y);
//base case
if(y == 0)
return 0;
//recursive case
System.out.print(x + " + ");
return x + recursiveMultiply(x, y-1);
答案 0 :(得分:0)
作为前两个条件,if(y>=1)
是无用的
public static int recursiveMultiply(int x, int y) {
if (y < 0) {
return recursiveMultiply(-x, -y);
}
if (y == 0) {
return 0;
}
System.out.print(x);
if (y != 1) {
System.out.print(" + ");
}
return x + recursiveMultiply(x, y - 1);
}
答案 1 :(得分:0)
public static void main(String [] args){
System.out.println("="+ recursiveMultiply(-6,-4));
}
private static int recursiveMultiply(int i, int j) {
if (j< 0) {
return recursiveMultiply(i, Math.abs(-j));
}
if (j == 0) {
return 0;
}
System.out.print(i);
if (j!= 1) {
System.out.print(" + ");
}
return i + recursiveMultiply(i, j - 1);
}