jeudi 6 décembre 2018

Addition in rand not working properly c++

The code is outputting random numbers in a two dimentional array. On p[i][6] I want to insert an average of the previous three fields but it for some reason it doesn't give me the right number.

srand ( time(NULL) );
int p[166][7];

for (int i = 0; i < 166; i++){
    for (int j = 0; j < 7; j++){
        p[i][0] = i+1;
        p[i][1] = rand() % 30;
        p[i][2] = rand() % 20;
        p[i][3] = rand() % 101;
        p[i][4] = rand() % 101;
        p[i][5] = rand() % 101;
        p[i][6] = (p[i][3] + p[i][4] + p[i][5]) / 3;
        cout << p[i][j] << " ";
    }

For instance when I run the code, it gives me back that p[i][3] = 18, p[i][4] = 88, p[i][5] = 72 and p[i][6] = 39, which is wrong. (18 + 88 + 72) / 3 = 59




Aucun commentaire:

Enregistrer un commentaire