0

C++ random 2d array with average

Can't get random numbers in range 1-100. The average is also wrong. Any advice is greatly appreciated. #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; int main() {    srand(time(NULL));    const int rows = 3;    const int cols = 3;    double sum = 0;    int grades[rows][cols];    int row, col;      for (int r = 0; r < rows; ++r) {        row = rand() % 100 + 0;        for (int c = 0; c < cols; ++c) {            col = rand() % 100 + 0;            grades[r][c] = (rand() % 100) + 0;            sum += grades[r][c];            cout << sum << " ";        }        double average =  sum / (rows + cols);        cout << "Average: " << average<<endl;        cout << endl;    }       return 0; }

15th Nov 2018, 12:53 AM
dominic smith
dominic smith - avatar
2 Respuestas
+ 11
Variables row and col do not appear to be needed, so we can remove those. To generate a number between 1 and 100 (inclusive), you have to add 1 to rand() % 100, not 0. Move double average = sum... till cout << endl out of the outer loop. Those are generated after you've completed all the iterations. Also, average should be sum/(rows*cols), not rows+cols. #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() {    srand(time(NULL));    const int rows = 3;    const int cols = 3;    double sum = 0;    int grades[rows][cols];    for (int r = 0; r < rows; ++r) {        for (int c = 0; c < cols; ++c) {            grades[r][c] = (rand() % 100) + 1;            sum += grades[r][c];         } }    double average =  sum / (rows * cols); cout << "Average: " << average << endl;  cout << endl;    return 0; }
15th Nov 2018, 1:30 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
thanks a lot Hasty Rei
15th Nov 2018, 8:42 PM
dominic smith
dominic smith - avatar