gpt4 book ai didi

c - 为什么我的按位除法函数会产生段错误?

转载 作者:行者123 更新时间:2023-11-30 14:23:37 24 4
gpt4 key购买 nike

我的代码如下,它适用于大多数输入,但我注意到,对于非常大的数字(对于特定示例,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;
}

最佳答案

bdiv 的问题很可能是由递归深度引起的。在您给出的示例中,您将把大约 1073741824 个帧放入堆栈中,基本上耗尽了分配的内存。

事实上,这个函数没有真正的理由需要递归。我可以很容易地转换为迭代解决方案,从而缓解堆栈问题。

关于c - 为什么我的按位除法函数会产生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12720182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com