0

I attach the working code to match an approximation of pi.

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <time.h>
using namespace std;

int tabSize=720; //odd number recommended, max 32767
int precision=10000000;

long double round=0;
int number1, number2;
int main()
{
    long double r=(long double)tabSize/2;
    long double r2=r*r;
    int s=tabSize/2+1;
    int tab[tabSize][tabSize];
    for(int i=0;i<tabSize;i++)
    {
        for(int j=0;j<tabSize;j++)
        {
            if((i-s)*(i-s)+(j-s)*(j-s)<=r2)
            {
                tab[i][j]=1;
            }
            else
            {
                tab[i][j]=2;
            }
        }
    }
    srand(time(NULL));
    for(int i=0;i<precision;i++)
    {
        number1=rand()%tabSize;
        number2=rand()%tabSize;
        if(tab[number1][number2]==1)
        {
            round++;
        }
    }
    round/=precision;
    long double pi=round*tabSize*tabSize/r2;
    cout << "Your pi approximation: " << setprecision(50) << pi << endl;
    return 0;
}

Everything works, but if I increase tabSize to 721 or more, script crash: "Process returned -1073741571 (0xC00000FD)". What is more, this is a max value in CodeBlocks, because in QT Creator under Linux I can enter up to 1446 to tabSize variable. 1447 or more cause the same crash "Process returned -1073741571 (0xC00000FD)". What is the reason? Where is my fault?

bartosz325
  • 61
  • 2
  • 7
  • [`using namespace std;` is a bad practice](https://stackoverflow.com/q/1452721/2176813), never use it. Additionally, note that `time.h` is a deprecated C-compatibility header in C++ - use `ctime` and friends instead. – tambre Dec 17 '17 at 16:41
  • It crashed with this web site's name. The tab array is getting too large to fit in the available stack space. 720 * 720 * 4 = 2 megabytes - 23.5 kb, that appears to just barely fit. A bit unusual btw, the default stack space is usually 1 megabytes. But ymmv. 1446 * 1446 * 4 = 8 megabytes. Check your toolset's linker docs for the option to increase the stack size. – Hans Passant Dec 17 '17 at 16:46
  • `int tab[tabSize][tabSize];` -- Please note that this isn't valid C++. Arrays in C++ must be declared using a compile-time constant to denote the number of entries, not a variable. – PaulMcKenzie Dec 17 '17 at 18:03

0 Answers0