繁体   English   中英

如何释放 memory

[英]How to deallocate memory

我有一个 void function 我主要调用它,我希望它每次调用时都使用一个新的 pi 值,而不是添加它们。 我觉得我应该为 Dir 类型的数组释放 memory,但我想不通。 实现如下:

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 的值。

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

换句话说,

   double numCicle;

应该

   double numCicle = 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM