我的任务是输入和读取()几个双变量并将它们存储在向量中,然后函数计算()应该计算存储在向量中的所有变量的总和及其平均值。我已经修复了这些功能,它们运行良好。问题在于最终函数 print() .. 该函数应该打印出结果 - 'sum' 和 'average' 变量。但是我的 print() 代码无法正常工作并打印出错误的数字。这是我的代码:
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
vector<double> read(){//this function works fine
cout << "Write some numbers with space between them?" << endl;
double numz;
vector<double> myvector;
do {
cin >> numz;
myvector.push_back (numz);
} while (numz);
return myvector;
}
void compute(double average, double sum, vector<double> &myvector){//this function works fine
//if i put cout in this function it calculates correctly
vector<double>::iterator it;
for ( it=myvector.begin() ; it < myvector.end()-1; it++ ){
sum += *it;
}
average = sum/myvector.size();
}
void print(double average, double sum){//this is printing out wrong numbers
cout.precision(2);
cout << sum << endl;
cout << fixed << average << endl;
}
int main (){
vector<double> myvector = read();
double average;
double sum;
compute(average, sum, myvector);
print(average, sum);//this is printing out wrong numbers
system("pause");
return 0;
}
在此先感谢您的帮助,我知道我的问题在于函数之间的变量传递,但是我花了一整天的时间调试和阅读教程,但没有任何运气。