用for循环C ++计算向量的平均值

时间:2016-03-15 16:08:20

标签: c++

目前正在进行c ++的入门课程,需要使用循环将文件中的值读取到向量中,然后将其打印到控制台。我已经能够这样做了,然后我需要使用for循环来找到平均值。我可能正在阅读其他代码,我已经查看了线索......但似乎无法找到很多帮助。

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() {

    ifstream numbers;
    numbers.open("G:\\numbers.dat"); // just a file of 10 integers.
    int i;
    vector<float> vectors;

    while(numbers >> i) {
        vectors.push_back(i);
    }

    for(int n=0; n < vectors.size(); ++n ){
        cout << vectors[n] << endl;
    }

    int avg;
    for(int k=0; k < vectors.size(); ++k){
        // not sure what to put here basically.
        cout << avg << endl;
    }


    numbers.close();

    return 0;
}

任何帮助非常感谢。感谢。

2 个答案:

答案 0 :(得分:1)

平均值是元素之和除以元素数。所以:

int avg;
int sumTotal = 0;
    for(int k=0; k < vectors.size(); ++k){
        // not sure what to put here basically.
        sumTotal += vectors[n];

    }
  avg = sumTotal / vectors.size();
 cout << avg << endl;

答案 1 :(得分:1)

请注意,在Tirma的解决方案中,for循环中的索引存在问题。应该是k,而不是n。

还请注意,我们也可以使用基于自动的循环来代替上述的for循环:

for (int vector: vectors)
{
    sumTotal+= vector;
}
相关问题