划分并行数组 C++

divide parallel arrays C++

我有一个关于划分并行数组的问题。我是 C++ 的新手。在我的程序中,我划分并行数组(atBats[] 和 hits[],并将结果存储在一个空数组中(batAvg[]。当我划分时,即使其他两个数组保存正确的数据,新数组仍然是空白的.我只需要知道为什么batAvg数组没有更新来存储新数据。

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

到目前为止一切正常,但 batAverage 函数是 batAvg 数组未正确存储数据的地方。该数组读取全零,即使它应该存储 694、417、389 和 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

这是我正在读入程序的文件中的数据:

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

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

括号内的两个数都是整数,所以表达式是整数。因此,如果 hits[i] < atBats[i] 结果为零,然后乘以 1000。

试试这个:

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

已编辑:1000.0 而不是 1000,因为所需的结果是双精度数。

我认为问题在于您没有通过引用传递参数 double batAvg[]。尝试:

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

编辑:我傻了,A.S.H应该是对的