我的C ++程序在计算Euler数

时间:2018-01-29 15:22:12

标签: c++ visual-c++ stack-overflow series eulers-number

enter image description here

这是我为解决上述系列而编写的C ++程序:

#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;

int factorial(int a)
{
    if (a > 1)
        return a * factorial(a - 1);
    else
        return 1;
}

float series(float x, int n, float b)
{
    if (abs(pow(x, n) / factorial(n)) < pow(10, -6) || abs(pow(x, n) / factorial(n)) == pow(10, -6)) { return b; }
    else return b = (pow(x, n) / factorial(n)) + series(x, n + 1, b);
}

int main()
{
    float x;
    cout << "Enter x: "<<endl;
    cin >> x;
    cout << "E^x = " << series(x,0,0);
    system("pause");
    return 0;
}

当abs(x)&lt; 2但是当abs(x)> = 2时出现此错误:

  

33b.exe中0x00F02539处的未处理异常:0xC00000FD:堆栈   溢出(参数:0x00000001,0x00F22FF8)。发生了   enter image description here

我想知道为什么会发生这种情况,我该如何解决?

2 个答案:

答案 0 :(得分:3)

你的问题是递归太深。请考虑循环。

float series(float x)
{
    const float epsilon = 1e-6f;
    double error = 1;
    double res = 1.f;
    int iter = 1;
    while (abs(error) > epsilon) {
        error *= (x / iter++);
        res += error;
        cout << error << endl;
    }
    return res;
}

int main()
{
    cout << "E^x = " << series(3);
    system("pause");
    return 0;
}

更清楚地了解会发生什么:

当您在另一个函数内调用函数时,将保存父函数的上下文,以便为新上下文腾出空间。当你创造了数百万的开始时,负责保存这些上下文的内存堆栈已经满了并且溢出。

这是Stack Overflow。

答案 1 :(得分:1)

 #include <iostream>
 #include <cmath>
 #include <cstdlib>
 using namespace std;
 int factorial[200];
 int Factorial(int a)
 {    if(a>0){
     factorial[a]=a * factorial[a-1];
         return factorial[a];
    }
    else
    factorial[a]=1;
    return 1;

 }

 double series(double x, int n, double b)
 {   double temp=(abs(pow(x, n)) / Factorial(n));
     if (temp <= 0.000001) { return b; }
     else return (temp + series(x, n + 1, b));
 }

 int main()
 {
     float x;
     cout << "Enter x: "<<endl;
     cin >> x;
     cout << "E^x = " << series(x,0,0);
     system("pause");
     return 0;
 }
这个解决方案正在发挥作用。所有我做的是我把你的代码删除abs(pow(x,n)/ factorial(n)),无论它重复和初始化到一个新的变量临时。然后而不是&lt; || ==你可以直接把&lt; =。而不是每次你可以给这个值来进一步减少时间时调用一个函数来计算.000001。但是我相信代码可能不起作用的原因是太多的递归。因此对于阶乘,我使用动态编程来降低其复杂性。上面的代码工作正常。

相关问题