我的代码在下面,它适用于大多数输入,但我注意到,对于非常大的数字(2147483647除以2作为特定示例),我得到分段错误并且程序停止工作。请注意,badd()和bsub()函数分别仅添加或减去整数。为什么我的按位分割函数会产生分段错误?
unsigned int bdiv(unsigned int dividend, unsigned int divisor){
int quotient = 1;
if (divisor == dividend)
{
return 1;
}
else if (dividend < divisor)
{ return -1; }// this represents dividing by zero
quotient = badd(quotient, bdiv(bsub(dividend, divisor), divisor));
return quotient;
}
我对我的bmult()函数也有点麻烦。它适用于某些值,但程序失败的值为-8192倍3.此功能也列出。预先感谢您的帮助。对此,我真的非常感激!
int bmult(int x,int y){
int total=0;
/*for (i = 31; i >= 0; i--)
{
total = total << 1;
if(y&1 ==1)
total = badd(total,x);
}
return total;*/
while (x != 0)
{
if ((x&1) != 0)
{
total = badd(total, y);
}
y <<= 1;
x >>= 1;
}
return total;
}
不是说我不知道猜测它们是什么,在你的代码中缺少两个可能很重要的函数。你可能也想把它们带进去。 – WhozCraig
告诉我们你在哪里得到segfault可能也很有用。 –
就像我说过的那样,bsub()和badd()函数只是简单地加上或减去两个整数,当输入我在描述中列出的值时发生故障。前两个函数起作用,所以我不想通过为他们显示代码来更长时间地提出问题。 – LulzCow