How can I change my code?

I have problem error E0513, C2297, C2040 are constantly output. What shall I do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include <iostream>
#include <cstdlib>
#include <locale.h>
#include <time.h>
#define N 2
#define X 5
using namespace std;
int main()

{
    int i, j, sum,a,c=0;  
    int E[N][X];        
    srand(time(NULL));
    cout <<  Matz -  << N << " x " << X << endl;
    for (i = 0; i < N; i++)  
    {
        for (j = 0; j < X; j++)
        {
            E[i][j] = rand() % 10; 
            cout << E[i][j] << " "; 
        }
        cout << "\n";    

    }
    for(i=0;i<X;i++)
    {
        sum += E[i];
        a = sum / X;
    }
    cout << a;
}
Last edited on
Line 14, ?? put quotes around Matz -.

E is a 2 dimensional array, line 27 you are accessing as a 1 dimensional array.

Not knowing what your output is supposed to show:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
   constexpr int ROWS { 2 };
   constexpr int COLS { 5 };

   srand((unsigned) time(NULL));

   int E[ROWS][COLS];

   std::cout << "Matz - " << ROWS << " x " << COLS << "\n\n";

   for (int row { }; row < ROWS; row++)
   {
      for (int col { }; col < COLS; col++)
      {
         E[row][col] = rand() % 10;

         std::cout << E[row][col] << ' ';
      }
      std::cout << '\n';
   }
   std::cout << '\n';

   int sum { };

   // don't you want a sum of all the numbers?
   // not those in just one row?
   for (int col { }; col < COLS; col++)
   {
      sum += E[0][col];
   }
   int a { sum / COLS };

   std::cout << a << '\n';
}
I have to get an integer.
Thanks for the help!
I have to get an integer.

Just saying you need an integer doesn't tell us what the program is supposed to do, other than generate 10 random numbers in a 2 x 5 2D array.

So what are you trying to do with those 10 integer random numbers?
This will give an int sum & average for each row:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <random>
#include <iostream>
#include <algorithm>
#include <numeric>

int main()
{
	const size_t noRow {2};
	const size_t noCol {5};

	auto rand {std::mt19937 {std::random_device {}()}};
	auto randNo {std::uniform_int_distribution<size_t> {0, 9}};

	int E[noRow][noCol] {};

	for (auto& r : E)
		for (auto& e : r)
			e = randNo(rand);

	// Sum and average per row

	for (const auto& r : E) {
		const auto sum {std::accumulate(std::begin(r), std::end(r), 0)};

		std::cout << "Row sum: " << sum << ", average (int): " << sum / noCol << '\n';
	}
}

Topic archived. No new replies allowed.