gpt4 book ai didi

c++ - 使用for循环C++计算 vector 的平均值

转载 作者:行者123 更新时间:2023-11-28 05:47:05 24 4
gpt4 key购买 nike

目前正在学习 C++ 入门类(class),需要使用循环将值从文件读取到 vector ,然后将其打印到控制台。我已经能够做到这一点,但是,然后我需要使用 for-loop 来找到平均值。我可能正在阅读其他代码以寻找线索……但似乎找不到太多帮助。

#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;
}

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

最佳答案

平均值是元素的总和除以元素的数量。所以:

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

关于c++ - 使用for循环C++计算 vector 的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36016484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com