10楼你写反了吧,左移是乘,右移是除啊!
cyhdahua的解释基本是我算法的本意。
如果各位觉得明白了,那不妨再测试一下自己的理解程度,请偿试用位运算完成任意两个整数(整型范围内的)的乘法运算。
话说cyhdahua这头像,我差点以为是佟湘玉
2012-10-25 09:12

2012-10-25 20:57
2012-10-25 21:24

2012-10-25 23:01
程序代码:#include<stdio.h>
//用位运算直接实现两数相乘
/*思路:
1.判断正负号
2.把负数转换成正数
3.正数2进制乘法,即
110
*101
------
110
+ 000
+110
就是一个数如果左移n位,并且最低位是1,那么另一个数就右移n位。
然后把右移后的结果相加
4.加上符号
*/
int mult_bit(int n,int m){
bool sign; //=n<0?(m<0? n=-n,m=-m,true:n=-n,false):(m>0?true:m=-m,false); //同号为true,并且把m,n转成正数(直接赋值为什么不行?)
if(n<0&&m<0||n>0&&m>0){
sign=true;
n<0?n=-n:n;
m<0?m=-m:m;
}
else{
sign=false;
n<0?n=-n:n;
m<0?m=-m:m;
}
int sum=0,temp=0,f;
for(int i=0;f=m>>i;i++){
if(f&1)temp=n<<i;else continue;
for(;f=sum&temp;sum^=temp,temp=f<<1);
sum^=temp;
}
return sign?sum:-sum;
}
int main(){
int a,b;
printf("Input two integer:");
while(scanf("%d%d",&a,&b))
printf("%d\nGO ON:\n",mult_bit(a,b));
return 0;
}已经很努力了,求指点,求改进
2012-10-26 23:20
程序代码:#include<stdio.h>
#include<math.h>
//用位运算直接实现两数相乘
/*思路:
1.判断正负号
2.把负数转换成正数
3.正数2进制乘法,即
110
*101
------
110
+ 000
+110
就是一个数如果左移n位,并且最低位是1,那么另一个数就右移n位。
然后把右移后的结果相加
4.加上符号
*/
int mult_bit(int n,int m){
int sum=0,temp=0,f;
n=abs(n),m=abs(m);
for(int i=0;f=m>>i;i++){
if(f&1)temp=n<<i;else continue;
for(;f=sum&temp;sum^=temp,temp=f<<1);
sum^=temp;
}
return (n^m)<0?-sum:sum;
}
int main(){
int x; x=-13.06;
int a,b;
printf("Input two integer:");
while(scanf("%d%d",&a,&b))
printf("%d\nGO ON:\n",mult_bit(a,b));
return 0;
}再贴一次
2012-10-27 08:12
2012-10-27 08:33
2012-10-27 09:02
程序代码:#include<stdio.h>
int mul(unsigned int a, unsigned int b)
{
unsigned int c, f, t;
for(c = 0; a && b; c ^= t, a <<= 1, b >>= 1)
for(t = b & 1 ? a : 0; f = c & t; c ^= t, t = f << 1);
return c;
}
int main()
{
int a, b;
scanf("%d%d", &a, &b);
printf("%d * %d = %d\n", a, b, mul(a, b));
return 0;
}

2012-10-27 09:33

2012-10-27 15:14