mult(a,b)
要示实现a*b
要用累加的方法来实现乘法
a,b为两个整数
如4*2=4+4,4*4=4+4+4+4
......
程序要求用递归实现

解决方案 »

  1.   

    int mult(int a,int b)
    {
        if b>0 then
        {
             int result = a;
             result += mult(a,b-1);
             return result;
        }
        else
        {
             return 0;
        }
    }
      

  2.   

    迭代:
    protected int mult(int a,int b)
    {
        if b>0 then
        {
             int result = a;
             result += mult(a,b-1);
             return result;
        }
        else
        {
             return 0;
        }
    }
      

  3.   

    继续叠代迭代:
    protected int mult(int a,int b)
    {
        if b>0 then
        {
             int result = a;
             result += mult(a,b-1);
             return result;
        }
        else
        {
             return 0;
        }
    }
      

  4.   

    万一其中一个不是 int 型的呢??楼上两位想的是不是太简单了呢???
      

  5.   

    作业题:(
    把楼上的答案修正一下,呵呵~~class test
    {
    static int mult(int a,int b)
    {
        if (b>0)
        {
             int result = a;
             result += mult(a,b-1);
             return result;
        }
        else
        {
             return 0;
        }
    }

    public static void main(String[] args)
    {
    System.out.print(mult(3,4));
    }
    }
      

  6.   

    不好意思,要考虑b为负数的情况,重写一下:class test
    {
    static int mult(int a,int b)
    {
        if (b<0) 
        {
         b=-b;
         a=-a;
        }
        if (b>0)
        {
             int result = a;
             result += mult(a,b-1);
             return result;
        }
        else
        {
             return 0;
        }
    }

    public static void main(String[] args)
    {
    System.out.println(mult(-3,4));
    System.out.println(mult(3,-4));
    System.out.println(mult(-3,-4));
    System.out.println(mult(3,4));
    }
    }