Получение значения выхода: -1,073,741,571 с простым кодом для вычисления n-го момента - PullRequest
1 голос
/ 03 мая 2020

У меня проблемы с этим кодом для вычисления n-го момента (например, центра масс, 1-го момента) массива случайных чисел. Я кодирую в C в Eclipse, эта ошибка также возникает, когда я пытаюсь скомпилировать с G cc. Когда я запускаю код для N <1000000, код работает нормально. Но когда я пытаюсь ввести более высокое значение N, например 1000000 или 1 миллион, код дает мне выходное значение -1,073,741,571 и не выводит моменты, как это должно быть. Я думаю, что это как-то связано с памятью. </p>

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//here we import the three libraries
//we start our main function
int main ()
{
    setbuf(stdout, NULL);
    //setbuf disables buffering so print statements print properly
    int i,N;

    unsigned int seed;
    double first,second,third,fourth,fifth,sixth,firsttot,secondtot,thirdtot,fourthtot,fifthtot,sixthtot;
    //here we declare the vars to be used
    printf("\nEnter number of iterations and seed");
    printf("\n");
    scanf("%i %u", &N, &seed);
    srand(seed);
    //asks user for input, scans the input, and takes the seed to set a starting point for the rand() function called in the for loop
    //since my R array depends on the user, i declare the array here, after the user inputs the size of the array
    double R[N];
    for (i=0;i<N;i=i+1)
    {
        R[i]=(double)rand()/RAND_MAX;
        //printf("%12.8lf \n",R[i]);
    }

    //the for loop sets R equal to a random value using our seed with (double)rand()
    printf("\n");
    //here, we have for loops to add up the individual nth moments for each point of the array
    firsttot = 0.0;
    for (i=0;i<N;i=i+1)
    {
        firsttot = firsttot + pow(R[i],1);
    }
    secondtot = 0.0;
    for (i=0;i<N;i=i+1)
    {
        secondtot = secondtot + pow(R[i],2);
    }
    thirdtot = 0.0;
    for (i=0;i<N;i=i+1)
    {
        thirdtot= thirdtot + pow(R[i],3);
    }
    fourthtot = 0.0;
    for (i=0;i<N;i=i+1)
    {
        fourthtot = fourthtot + pow(R[i],4);
    }

    fifthtot = 0.0;
    for (i=0;i<N;i=i+1)
    {
        fifthtot = fifthtot + pow(R[i],5);
    }
    sixthtot = 0.0;
    for (i=0;i<N;i=i+1)
    {
        sixthtot = sixthtot + pow(R[i],6);
    }

    //now, we take the actual nth moment by dividing each total by N;
    first = firsttot/N;
    second = secondtot/N;
    third = thirdtot/N;
    fourth = fourthtot/N;
    fifth = fifthtot/N;
    sixth = sixthtot/N;
    printf("\nThe first moment is:   %lf",first);
    printf("\nThe second moment is:   %lf",second);
    printf("\nThe third moment is:   %lf",third);
    printf("\nThe fourth moment is:   %lf",fourth);
    printf("\nThe fifth moment is:   %lf",fifth);
    printf("\nThe sixth moment is:   %lf",sixth);
    return 0;
}

1 Ответ

1 голос
/ 04 мая 2020

В вашем коде вы строите массив в стеке размером N: int R[N]

Я подозреваю, что это вызывает переполнение стека для достаточно больших значений N. Можете ли вы увидеть, воспроизводит ли поведение, если вы замените свою строку int R[N] на int* R = malloc(sizeof(*R) * N);

, используя mallo c, чтобы распределить массив R в куче вместо использования стека, что позволит избежать возможного переполнения стека

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...