概率计算器中的分段错误

时间:2014-04-23 21:54:46

标签: c++ arrays recursion probability

我在linux上编译它。它将编译并运行,但是当我输入n和p的值时,这就是我的终端的样子:

7 1.0 分段错误(核心转储)

在这种情况下,7是n的输入,1.0是p的输入。我尝试过不同的价值观。我们的想法是使用动态编程通过递归填充2D数组概率。如果您需要更多信息,请告诉我,但这是整个代码。

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{

  int n;
  double p;

  cin >> n;
  cin >> p;

  cout << n;
  cout << p;

  cout << "Initializing array.";
  double** probability = new double*[n];
  for(int i = 0; i < n; ++i)
  {
     probability[i] = new double[n];
  }

  //cout << "Beginning filling i loop.";
  for(int i = 0; i < n; i++)
  {
     probability[i][0] = 0;
  }
  //cout << "Beginning filling j loop.";

  for(int j = 0; j < n; j++)
  {
     probability[0][j] = 1;
  }

  //cout << "Beginning filling nested loop.";
  for(int i = 1; i< n; i++)
  {
     for(int j = 1; j< n; j++)
     {
        probability[i][j] = (p * probability[i-1][j]) + ((1-p) * probability[i][j-1]);
     }
  }

  cout << "Probability: ";
  cout << probability[n][n];

  //cleanup
  for(int i = 0; i < n; ++i)
  {
    delete probability[i] ;
  }
  delete probability;

  return 0;
}

1 个答案:

答案 0 :(得分:1)

cout << probability[n][n];

probability[][]是一个n乘n数组。最后一个元素是probability[n-1][n-1],所以你运行数组的末尾并调用未定义的行为。