divide parallel arrays C++

557 Views Asked by At

I have a question about dividing parallel arrays. I'm fairly new to C++. In my program I'm dividing parallel arrays (atBats[] and hits[], and storing the results in an empty array (batAvg[]. When I divide, the new array remains blank even though the other two arrays are holding correct data. I just need to know why the batAvg array is not updating to store the new data.

int main() {

    //declare variables and arrays
    const int SIZE = 20;
    int playerNum[SIZE],
        atBats[SIZE],
        hits[SIZE],
        runs[SIZE],
        rbis[SIZE];
    double batAvg[SIZE];
    int numberPlayers;

    //Load number of players from the loadArrays method
    numberPlayers = loadArrays(playerNum, atBats, hits, runs, rbis);
    batAverage(atBats, hits, batAvg, numberPlayers);

    system("pause");

    return 0;

}//end main

int loadArrays(int playerNum[], int atBats[], int hits[], int runs[], int rbis[]) {

    //Define variables
    int i = 0;

    //Open file and read arrays
    ifstream inputFile;
    inputFile.open("BaseballStats.txt");

    //Let user know if the file fails to open
    if (inputFile.fail())
        cout << "There was an error opening the file.\n";

    //Load the arrays from the file and increment count each loop
    while (inputFile >> playerNum[i]) {

        inputFile >> atBats[i];
        inputFile >> hits[i];
        inputFile >> runs[i];
        inputFile >> rbis[i];

        i++;

    }//end while loop

    //Close file and return count as reference to the number of players
    inputFile.close();

    return i;

}//end loadArrays method

Everything is fine up to this point, but the batAverage function is where the batAvg array is not storing data correctly. The array reads all zeros, even though it should be storing numbers such as 694, 417, 389, and 488.

void batAverage(int atBats[], int hits[], double batAvg[], int numberPlayers) {

    for (int i = 0; i < numberPlayers; i++) {

        batAvg[i] = (hits[i] / atBats[i]) * 1000;

    }//end for loop

}//end batAverage method

This is the data from the file I am reading into the program:

10 36 25 2 5
2 12 5 0 1
34 18 7 1 0
63 41 20 4 2
12 10 3 1 0
14 2 1 1 1
27 55 27 10 8
8 27 12 3 4
42 32 8 2 1
33 19 4 1 0

2

There are 2 best solutions below

2
On BEST ANSWER
 batAvg[i] = (hits[i] / atBats[i]) * 1000;

inside the parenthesis, both numbers are integers, so the expression is an integer. So if hits[i] < atBats[i] the result is zero, which then you multiply by 1000.

Try this instead:

 batAvg[i] = (1000.0 * hits[i]) / atBats[i];

EDITED: 1000.0 instead of 1000 since the required result is a double.

3
On

I think the problem is that you're not passing the parameter double batAvg[] by reference. Try:

void batAverage(int atBats[], int hits[], double& batAvg[], int numberPlayers)

Edit: I'm stupid and A.S.H should be right