计算char数组的平均数

时间:2017-10-15 21:10:34

标签: c++

我试图计算一个char数组中几个数字的平均值。这样做的原因是我从文本文档中导入了数据,并且我每隔第二行只读取一次以获得我想要的数字。

现在我需要从这些数字中取出平均数,但我不能让它发挥作用。我开始对此感到生气,我觉得解决方案会相当简单。

编辑: 该文件由名称和数字组成。即:

杰森史密斯

32

Mary Jane

52

Stevie Wonder

68

迈克尔杰克逊

59

#include <fstream>
#include <iostream>

using namespace std;

double averageNum(char array[], int size) { // A function to calculate the average number

    int sum = 0;
    double avg;

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

        array[i]+= sum;

    }

    avg = sum / size;
    return avg;
}


int main(){

    char age [50][30];
    double avg;
    int rows = 0;

    ifstream elevInfo("elevinfo.txt"); // Opens a stream to get data from the document

    if (! elevInfo){    // Error message if the file couldn't be found

        cout << "Could not find the file elevinfo.txt" << endl;
        return (1);
    }


    while(elevInfo.getline(age[rows/2], 30)){ // Reading every 2nd line to an array

        rows++;

    }

    avg = averageNum(age[], rows); // Function call with the numbers from the array and the variable rows as a pointer
    cout << "Average age equals: " << avg << endl;
}

1 个答案:

答案 0 :(得分:0)

这是解决您问题的众多可能解决方案之一:

int main()
{
    // Opens a stream to get data from the document
    ifstream elevInfo("elevinfo.txt"); 
    // Error message if the file couldn't be found
    if (!elevInfo)
    {
        cout << "Could not find the file elevinfo.txt" << endl;
        return (1);
    }

    int sum = 0;
    int lineCounter = 0;

    // loop till end of file
    while (!elevInfo.eof())
    {
        // prepare buffer
        char line[30];
        // read line into buffer
        elevInfo.getline(line, 30);

        // do this every second line
        if (lineCounter % 2 == 1)
        {
            // get age as int using function atoi()
            int age = atoi(line);
            // increase sum by the current age
            sum += age;
        }
        // increment line-counter
        lineCounter++;
    }

    // calculate the average
    // divide lineCounter by 2 because only every second line in your file contains an age
    double avg = sum / (lineCounter / 2.0);
    cout << "Average age equals: " << avg << endl;

    return 0;
}

正如您所看到的,它也不需要函数averageNum