-3

Im trying to run the following code

  int salespersons=0,weeks=0,days=5;

  double weekly_sales[weeks][salespersons][days];
  double total_weekly_sales[weeks];


for(int w=0; w < weeks;w++)
  {
     for(int d =0; d < days; d++)
     {  

        for(int s=0; s < salespersons; s++)
        {

           {
              total_weekly_sales[w]+=weekly_sales[w][s][d];
              total_overall_weekly_sales[s]+= weekly_sales[w][s][d];

           }
        }  
     }

  }

when I run only..

cout << total_weekly_sales[0];

I get NaN therefore skipping the first section of the array while processing the rest.

3 Answers3

5
double weekly_sales[weeks][salespersons][days];
double total_weekly_sales[weeks];

Uninitialized.

Edit: this is how you should initialize them:

double weekly_sales[weeks][salespersons][days] = { { { 0.0 } } };
  • How would I initialize this properly. I further defined my question for clarity. –  Apr 04 '13 at 19:24
  • Hopefully just `= {0.0}` will work soon enough if the proposal goes well. – chris Apr 04 '13 at 19:33
  • Just adding = { { { 0.0 } } }; makes it give the error "variable-sized object 'weekly_sales' may not be initialized" –  Apr 04 '13 at 19:38
  • I found that adding weekly_sales[0][0][0]=0; total_weekly_sales[0]=0; makes it work –  Apr 04 '13 at 19:46
  • @Some guy: That is because the dimensions of the array are not constant. Change the line `int salespersons=0,weeks=0,days=5;` to `int const salespersons=0,weeks=0,days=5;` – Arun Apr 04 '13 at 19:47
2
double total_weekly_sales[weeks];

total_weekly_sales[w]+=weekly_sales[w][s][d];

You are adding to an uninitialized variable.

And printing an uninitialized variable

cout << total_weekly_sales[0];
Matt
  • 74
  • 3
1

You try with the code and you've initialized all variables

    int weeks=2,salepersons=3,days=1;

        double weekly_sales[weeks][salespersons][days];
          double total_weekly_sales[weeks];

    for(int w=0; w < weeks;w++)
      {
         for(int d =0; d < days; d++)
         {  
        for(int s=0; s < salespersons; s++)
        {

           {
              total_weekly_sales[w]=2;
              weekly_sales[w][s][d]=1;

           }
        }  
     }

  }


    for(int w=0; w < weeks;w++)
      {
         for(int d =0; d < days; d++)
         {  

            for(int s=0; s < salespersons; s++)
            {

               {
                  total_weekly_sales[w]+=weekly_sales[w][s][d];
                  total_overall_weekly_sales[s]+= weekly_sales[w][s][d];

               }
            }  
         }

      }

And use the library!!!

Mirko Cianfarani
  • 2,023
  • 1
  • 23
  • 39