如何释放内存

约翰·卡特

我有一个在主函数中调用的void函数,我希望它在每次调用时都使用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的值。

迈克猫

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

换一种说法,

   double numCicle;

应该

   double numCicle = 0;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章