如何释放内存

时间:2020-12-27 15:33:39

标签: c++ memory-management

我有一个 void 函数,我在 main 中调用它,我希望它每次调用时都为 pi 使用一个新值,而不是添加它们。我想我应该为 Dir 类型的数组释放内存,但我无法弄清楚。实现如下:

void throwSeries(int n)
{
   double pi;
   double faults;
   double numCicle;
   Dir c[n];

   int count = 0;
   for (int i = 0; i < n; i++)
   {
       c[i] = someFun();   // Returns type Dir
       if (below(c[i]))
       {
           numCicle++;
       }
   }
   pi = 4 * (numCicle / (double) n);
   faults = ((pi - M_PI) / M_PI) * 100;

   cout << setw(15) << setfill(' ') << n;
   cout << fixed << setprecision(5);
   cout<< setw(15)<< setfill(' ')  << pi << setw(15)<< setfill(' ') ;

   cout << fixed << setprecision(1);
   cout << faults << endl;
}

int main()
{
   system("CLS");
   srand(time(0));

   cout << setw(15) << "n" << setw(15) << "pi" << setw(15) << "faults" << endl;
   cout << setw(15) << setfill('-') << "|"<< setw(15) << setfill('-') << "|";
   cout << "--------------" << endl;

   int n = 0;
   for (int i = 0; i < 100; i++)
   {
       n += 100;
       throwSeries(n);
   }
   
   return 0;
}

打印示例如下:

              n             pi     Rel. fault
--------------|--------------|--------------
            100        3.12000           -0.7
            200        4.66000           48.3
            300        6.28000           99.9
            400        7.80000          148.3
            500        9.40000          199.2
            600       10.76000          242.5

并且不应在每次迭代中添加 pi 的值。

1 个答案:

答案 0 :(得分:0)

您必须先初始化 numCicle,然后再向其添加内容。

换句话说,

   double numCicle;

应该

   double numCicle = 0;
相关问题