我正在尝试将两个数字相乘但不应使用*运算符的代码。我写了这段代码,但没有给出预期的解决方案。
#include<stdio.h>
#include<stdlib.h>
int main(int ar,char *arg[])
{
long int a;
long int b;
sscanf(arg[1],"%ld",&a);
sscanf(arg[2],"%ld",&b);
long int count=0;
long int temp=b;
long int prod=0;
while(temp>0)
{
count=0;
while(temp/2>0)
{
temp/=2;
count++;
}
prod+=a<<(count);
temp=b-(1<<count);
}
//printf("%ld %d\n",count,1<<count);
printf("%ld\n",prod);
return 0;
}
有人可以解释代码中的错误吗?
答案 0 :(得分:1)
以这种方式编辑你的while循环。
while(temp>0)
{
count=0;
while(temp/2>0)
{
temp/=2;
count++;
}
prod+=a<<(count);
temp=b-(1<<count);
b=temp //<--
}
答案 1 :(得分:1)
vinayawsm已经给出了解决方案。我想你可能想考虑从LSB解决它。 = d
while(b>0)
{
if (b % 2 == 1)
prod+=a;
a=a<<1;
b=b>>1;
}
答案 2 :(得分:-1)
class Multiply
{
public static void main(String [] args)
{
int a,b,value=0;
a=7;
b=4;
for(int i=1;i<=b;i++){
value+=a;
}
System.out.println("Multiplication is:\t" + value);
}