【问题标题】:divide parallel arrays C++ [duplicate]划分并行数组C ++ [重复]
【发布时间】:2015-05-26 22:32:53
【问题描述】:

我有一个关于划分并行数组的问题。我对 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] 是整数,结果是整数?请改用batAvg[i] = hits[i] * 1000. / atBats[i];。 (不要忘记 1000 之后的点)

标签: c++ arrays integer-division parallel-arrays


【解决方案1】:
 batAvg[i] = (hits[i] / atBats[i]) * 1000;

在括号内,两个数字都是整数,所以表达式是整数。因此,如果 hits[i]

试试这个:

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

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

【讨论】:

  • 仍然进行整数除法。由于batAvg[i]double,我建议在1000 后面加一个点。
  • @nwp 是的,但这里没有害处,因为无论如何结果都会以整数形式存储。编辑:哎呀对不起,你是对的,我会编辑。
【解决方案2】:

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

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

编辑:我很愚蠢,A.S.H 应该是对的

【讨论】:

  • 不,这不是这里的问题。 double batAvg[]double *batAvg 一样工作。
  • 我不知道,在我的大学里我们会使用vector batAvg。谢谢!那么 A.S.H 是对的。
  • std::vector 通常是要走的路!如果不经常发生错误答案,请不要担心发布错误答案(尽管您当然应该确信自己是对的)。它仍然发生在我身上。在这种情况下(答案是错误的,并且不会对已接受的答案添加任何有用的内容),您可能会考虑删除您的答案。
猜你喜欢
  • 2016-08-05
  • 2023-03-10
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多