我有一个关于划分并行数组的问题。我对 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