问题:
每进行一次递归,都会在栈上多加一层,所以递归太深的话会出现数据溢出的错误。函数调用层次过深,每调用一次,函数的参数、局部变量等信息就压一次栈。
#include<iostream>
using namespace std;
int def(int n) {
if (n <= 1)
return 1;
else
return def(n -1) * n;
}
int main() {
cout << def(10);//可以出现正常的值
cout<<def(100);//不会出现正常结果
}
解决办法:
看了好多博客:
1.尾递归
int fact_iter(int num, int product) {
if (num == 1)
return product;
return fact_iter(num - 1, num * product);
}
不过根据实验,这个也不行。
2.数组法
利用数组来反向存储数据,并在最后反向输出结果。
#include<iostream>
using namespace std;
#include<string>
const int MAX = 3000;
int a[MAX];
int fac(int n) {
memset(a, 0, sizeof(a));//初始化0;下面的a[j] = a[j] * i + c计算过程中会用到a[j]=0
int top = 0;//最高位
a[0] = 1;
int c = 0;//用于判断是否进位,也就是j是否+1。
for (int i = 2; i <= n; i++) {//i为用来阶乘的数字,就是2~n之间的数字
for (int j = 0; j <= top; j++) { //j循环用来将计算出来的结果按位分割并存储到数组中
a[j] = a[j] * i + c;
c = a[j] / 10;//c就是下一次再次进入j循环时的a[j]初始值,结合下面的判断语句
//如果这里的c<10,top最高位就没必要再加了,如果c>10,则继续分割,知道c<10为止
if (j == top && c >= 1) {
top++;
}
a[j] = a[j] % 10;//取余得到第j位上该放置的数字
}
}
for (int i = top; i >= 0; --i) {
cout << a[i];
}
return 0;
}
int main() {
int n;
cout << "请输入一个数字n" << endl;
cin >> n;
fac(n);
}
这个用来算阶乘的效果很好:不会连100都算不了,可以看到下面连一千的阶乘都算的出来,只要不超过数组的限制。