int mult(int a,int b) { if b>0 then { int result = a; result += mult(a,b-1); return result; } else { return 0; } }
迭代: protected int mult(int a,int b) { if b>0 then { int result = a; result += mult(a,b-1); return result; } else { return 0; } }
继续叠代迭代: protected int mult(int a,int b) { if b>0 then { int result = a; result += mult(a,b-1); return result; } else { return 0; } }
万一其中一个不是 int 型的呢??楼上两位想的是不是太简单了呢???
作业题:( 把楼上的答案修正一下,呵呵~~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)); } }
不好意思,要考虑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; } }
{
if b>0 then
{
int result = a;
result += mult(a,b-1);
return result;
}
else
{
return 0;
}
}
protected int mult(int a,int b)
{
if b>0 then
{
int result = a;
result += mult(a,b-1);
return result;
}
else
{
return 0;
}
}
protected int mult(int a,int b)
{
if b>0 then
{
int result = a;
result += mult(a,b-1);
return result;
}
else
{
return 0;
}
}
把楼上的答案修正一下,呵呵~~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));
}
}
{
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));
}
}