Outputs wrong seed number

Hello! So I have to make a program in c++ that returns the average of all the numbers in a 2d array, and it gets one case right. When the dimensions are 1 and 1, it returns 7 when the seed is 75. But any other case outputs a correct number. Is the seed statement wrong?

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
40
41
42
43
   #include <iostream>
    #include <ctime>
    using namespace std;

    const int NUM_ROWS = 7;
    const int NUM_COLS = 9;

    double getArrayAverage(int myArray[NUM_ROWS][NUM_COLS], int rows, int cols);

    int main() {
       const int NUM_ROWS = 7;
       const int NUM_COLS = 9;
       int seed;
       int array[NUM_ROWS][NUM_COLS];
       double num = 0;
       
       cin >> seed;
       
       srand(seed);
       
       for (int i = 0; i < NUM_ROWS; i++) {
          for (int j = 0; i < NUM_COLS; i++) {
             array[i][j] = rand() % 10 + 1;
             }
          } 
          
          num = getArrayAverage(array, NUM_ROWS, NUM_COLS);
          cout << num << endl;
          return 0;
       }
       
       double getArrayAverage(int array[NUM_ROWS][NUM_COLS], int rows, int cols) {
          int sum = 0;
          double average = 0.0;
          for (int i = 0; i < rows; i++) {
             for (int j = 0; i < cols; i++) {
                sum = sum + array[i][j];
                }
             }
             average = sum / (rows * cols);
             return average;
             
          }
I don't understand. Why is 7 an incorrect output? The implementation of rand() doesn't guarantee that rand() = seed immediately after srand(seed).

Also, note that on line 40 you're performing an integer division. To perform a floating-point division cast both operands to double.
Last edited on
So 7 is the only correct output that it gets out of the five tests, and that's when you do
getArrayAverage(ary, 1, 1) and seed = 75. But if you call getArrayAverage(ary, 7, 9) when the seed is 55, it outputs 0.761905 when it should output 4.77778.
You have written i where you mean j on both of lines 22 and 36. (Two times on each of those lines).

That's in addition to the integer division problem on line 40 that @helios noted.

Please indent properly. It's difficult to see where main() ends.
Last edited on
Topic archived. No new replies allowed.