2016-03-03 43 views
0

我正在使用递归在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次)。这是我的代码到目前为止。在代码中,我写了一个注释,它应该被写入(例子)。谢谢。使用递归进行Java乘法

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

    } 

} 
+0

是否存在遇到代码的特定问题? – Castaglia

+0

问题是我不知道如何将产品分解成更小的数字并将其显示给用户。正如我在例子中所说的(10 * 5 = 50)。现在,我想在屏幕上将该产品编写为5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 – Ivanko

回答

3

一个StringBuilder应defiend为

StringBuilder buf = new StringBuilder (a); 

完成后通过这个StringBuilder的paramater为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)); 
     } 
    } 

    } 

} 

然后,只需打印输出其价值

+0

击败我:-) –

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

     } 
} 
+0

这两个例子都帮助我理解如何实现我需要。唯一的事情就是格式化。在这两种情况下,最后一个较小数字的末尾都有一个+号。这是我的意思。输出:输入第一个数字:10 输入第二个数字:5 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 10和5的乘积为:50 – Ivanko

+0

在上面的代码中,我已经关心最后的“+”符号。 –

+0

对不起,你做到了。我感谢您的帮助。现在我发现不同的问题,当我把10作为第一个数字和5作为第二个数字,这里是输出:输入第一个数字:10 输入第二个数字:5 10 * 5 = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 10和5的乘积是:46(不知道它为什么是46)另外,我试着写出“10和5的乘积是50”,然后在下面写道“It也可写成:5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5。 – Ivanko