使用递归的Java乘法

时间:2016-03-03 04:10:09

标签: java recursion multiplication

我正在用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));
        }
    }

  }

}

2 个答案:

答案 0 :(得分:3)

StringBuilder应该是

do-while

将此StringBuilder参数传递给StringBuilder buf = new StringBuilder (a);

然后将multiRec更改为

multiRec

然后完成时只需打印出其值

答案 1 :(得分:0)

    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));
            }
        }

      }
}