我有这段代码,它从文件中读取输入并将其存储在 vector 中。到目前为止,我已经得到它给我 vector 内值的总和,并使用总和给出值的平均值。
我现在想做的是学习如何再次访问 vector 并从 vector 的每个元素中减去一个值,然后再次打印出来。例如,一旦计算出总和和平均值,我希望能够在终端中重新打印每个值减去平均值。有什么建议/例子吗?
#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
fstream input;
input.open("input.txt");
double d;
vector<double> v;
cout << "The values in the file input.txt are: " << endl;
while (input >> d)
{
cout << d << endl;
v.push_back(d);
}
double total = 0.0;
double mean = 0.0;
double sub = 0.0;
for (int i = 0; i < v.size(); i++)
{
total += v[i];
mean = total / v.size();
sub = v[i] -= mean;
}
cout << "The sum of the values is: " << total << endl;
cout << "The mean value is: " << mean << endl;
cout << sub << endl;
}
最佳答案
您可以像访问数组一样简单地访问它,即 v[i] = v[i] - some_num;
关于c++ - 如何更改 vector 中元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4807709/