求一个2个数乘法的JAVA程序

来源:百度知道 编辑:UC知道 时间:2024/06/30 19:11:04
利用简单的循环叠加实现乘法运算,当然要考虑2个数的正负情况还有0.比如有2个数a,b.第1种a<0,b<0.第2种a<0,b>0.第3种a>0,b>0.第4种a>0,b<0.还有2个数各为0和都为0的情况.因为JAVA学的不是很好,所以请大家帮忙下.
补充下,是利用加法实现乘法.

public int caiculate(int a, int b){
int result = 0;
int tempA = Math.abs(a);
int tempB = Math.abs(b);
for(int i = 0, i < tempA, ++i)
result += tempB;
if ((a < 0 && b > 0) || (a > 0 && b < 0))
return (0 - result);
else
return result;
}

不明白你的意思,是用加法实现乘法么?
--------------------------------
public static int test1(int a,int b){
int f=1; //确定结果的符号
int result=0;
if(a==0||b==0) return 0;
if(a<0)f*=-1;
if(b<0)f*=-1;
a=Math.abs(a);
b=Math.abs(b);
for(int i=1;i<=b;i++){
result+=a; //循环加绝对值
}
result*=f; //给结果加上符号
return result;
}

//现在这个估计比刚才的效率更高一点