如何解决细分故障|计算阶乘|索引不足
我在在线IDE上解决的许多问题中都遇到了这种细分错误,但无法完全理解此问题并因此解决。请帮助我。
我知道它有时可能是由于堆栈溢出而发生的,因此,我应该使用堆内存。但是该怎么做?
// calculate factorial of really large numbers
#include<iostream>
using namespace std;
#define MAX 500
int multiply(int arr[],int x,int len)
{
int carry = 0;
int i = 0;
int temp = 0;
for(; i < len; i++)
{
// multiply each digit w the number x and store the carry to be added in the next number
temp = 0;
temp = x * arr[i] + carry;
arr[i] = (temp%10);
carry = temp/10;
}
// if end carry is also generated,even that has to be accomodated in the ans
while(carry != 0) //18 === 8 1
{
temp = carry%10;
carry /= 10;
arr[i] = temp;
len++;
i++;
}
// final length of the number is returned so that it can be printed easily
return len;
}
void factorial(int n)
{
int arr[MAX];
// The array initially contains 1
arr[0] = 1;
int arrLeng = 1;
// multiply the nth number with n+1 to obtain the factorial
for(int i = 2; i <=n; i++)
arrLeng = multiply(arr,i,arrLeng);
// print the final ans array though in reverse order
for(int i = arrLeng-1; i >= 0; i--)
cout<<arr[i];
cout<<endl;
}
int main()
{
// input the number
int n;
cin>>n;
// call the main function
factorial(n);
return 0;
}
解决方法
arrLeng
超过了硬编码的MAX 500的限制。
您应该始终检查索引。它不应超过MAX限制。这不是堆栈或堆上的内存分配问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。